blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fe5729ea3497b549f1d015cad9dafd13fa4cd103 | 0fca1251b4b01a6a5c684e4b834265ccae401d17 | /lab05-raytracer/RayTracer/utility.h | e388cd6d3de2b45b69f94a981d67662b3c71f994 | [] | no_license | mikathesmith/ComputerGraphics | 42cec1b99055d438e7b343e22f7777359283aec1 | 952c02899bbc629911866d6d7d9b9cf3acf1cef2 | refs/heads/master | 2021-01-20T02:38:00.186539 | 2017-05-22T05:44:55 | 2017-05-22T05:44:55 | 89,431,602 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,720 | h | #pragma once
#ifndef UTILITY_H_INCLUDED
#define UTILITY_H_INCLUDED
#include <cmath>
#include <limits>
/** \file
* \brief General utility functions.
*/
const double epsilon = 1e-6; //!< Small number for checking when things are almost zero
const double infinity = std::numeric_limits<double>::max(); //!< Very large number, bigger than any sensible distance
/**
* \brief Convert degrees to radians.
*
* C++ mathematical functions expect angles in radians, but many people think
* in degrees. The high level Transform functions expect parameters in degrees
* and this function, along with deg2rad(), converts between the two.
*
* \param deg An angle measured in degrees.
* \return The angle measured in radians.
*/
inline double deg2rad(double deg) {
return deg*M_PI/180;
}
/**
* \brief Convert radians to degrees.
*
* C++ mathematical functions expect angles in radians, but many people think
* in degrees. The high level Transform functions expect parameters in degrees
* and this function, along with rad2deg(), converts between the two.
*
* \param rad An angle measured in radians.
* \return The angle measured in degrees.
*/
inline double rad2deg(double rad) {
return rad*180/M_PI;
}
/**
* \brief Return the sign of a number.
*
* This function returns +1 for positive numbers, -1 for negative numbers
* and 0 for zero values. Since rounding can cause non-zero values,
*
* \param val The value to check the sign of.
* \return 0, +1, or -1 depending on the sign of \c val.
*/
inline int sign(double val) {
if (std::abs(val) < epsilon) return 0;
if (val < 0) return -1;
return 1;
}
#endif // UTILITY_H_INCLUDED | [
"mismith@oucs1510.otago.ac.nz"
] | mismith@oucs1510.otago.ac.nz |
7b831b03a5a3123b6da2692ae2ea9dc7c900801c | c0dffa026eb98d46c9c48d54dc8fd33062667bb3 | /f9_os/src/xv6cpp/os.cpp | 8a8b14a7947945cf531147dd0a1ae838fef85c52 | [
"Apache-2.0"
] | permissive | weimingtom/arm-cortex-v7-unix | 322b7f339a62a016393d5dba44b290116ff5d23b | cd499fa94d6ee6cd78a31387f3512d997335df52 | refs/heads/master | 2022-06-02T21:37:11.113487 | 2017-07-21T13:14:42 | 2017-07-21T13:14:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 660 | cpp | /*
* os.cpp
*
* Created on: Apr 18, 2017
* Author: warlo
*/
#include "os.h"
#include <diag\Trace.h>
namespace xv6 {
#if 0
enum class irq_prio {
Critical = 0,
Clock = 1,
Tty = 2,
Bio = 3,
Normal = 15,
};
#endif
static const char* irq_proi_string[] = {
// [(int)irq_prio::Critical] "Critical",
};
// sleep wakeup fuctions, fake ones are in the os.cpp
void wakeup(void *p){
trace_printf("Woke up pointer: %08X\n", (long)p);
}
void sleep(void* p, irq_prio pri){
trace_printf("Sleeping pointer: %08X, pri = %s\n", (long)p, irq_proi_string[(int)pri]);
assert(0); // have to die cause sleep not working yet
}
}; /* namespace xv6 */
| [
"warlockd@gmail.com"
] | warlockd@gmail.com |
1d1156d24602f99ecf7816b9016131f747ce3d36 | ed226331026fff14a929aaaed72b9ab2591d442d | /ch9/Iterator/DinerMenuIterator.cpp | 86f58f38eec5c3608d2d2203c5e55b00654bf54c | [] | no_license | yldbear77/design-patterns | 0574c908aea9dffb9e335f00666c0428b02a9db3 | eec21577cdd756d01b08b2cfae54ef20dece387a | refs/heads/master | 2023-05-09T03:56:13.383059 | 2021-05-27T14:12:59 | 2021-05-27T14:12:59 | 348,615,262 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | cpp | #include "DinerMenuIterator.h"
MenuItem DinerMenuIterator::next() {
MenuItem item = items[position];
++position;
return item;
}
bool DinerMenuIterator::HasNext() {
if (position >= DinerMenu::MAX_ITEMS || items[position].GetName() == "") return false;
return true;
} | [
"yldbear77@gmail.com"
] | yldbear77@gmail.com |
a6b49abc137bb61aa01cad690adde2c71f59bba5 | 2d495c7c0d1fc5cc2f93d8589d171582f664c5ec | /Lab1/Reverse/code.cpp | a13f85ab6b1f9154448eccac80acde2d0dab3999 | [] | no_license | RyanSaini/UCM-CSE165-Labs | 14247487856e61df82107f592e26056f286d8710 | 5e9f88ab0a669fa15b893b72401d60a6d837d676 | refs/heads/master | 2023-05-10T08:43:24.865729 | 2021-06-14T22:31:31 | 2021-06-14T22:31:31 | 376,971,783 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 314 | cpp | #include <iostream>
#include <math.h>
using namespace std;
int main(int argc, const char * argv[]) {
double a, b, c;
cin >> a;
cin >> b;
cin >> c;
cout << (-b + (sqrt((b * b) - (4 * a * c)))) / (2 * a) <<endl;
cout << (-b - (sqrt((b*b) - (4 * a * c)))) / (2 * a ) <<endl;
}
| [
"61637919+RyanSaini@users.noreply.github.com"
] | 61637919+RyanSaini@users.noreply.github.com |
d8e3cc1b5acfd5b2385cb1a1bb3bc36d2b2b0a7b | 059d4ec80fd1de74dabef3b984ad8c55243d1fdf | /PuyoPuyoGame/Pair.cpp | b3305dc062be23fca564ebe11344c885d7810bd0 | [] | no_license | darthcarlos90/PuyoPuyoGame | aa784513cd034ba67954fde3aefae8dc20965e4a | cab9d5357207d44e0cb4622ca6071e06043e26c0 | refs/heads/master | 2016-08-11T13:00:52.311843 | 2016-02-20T06:15:47 | 2016-02-20T06:15:47 | 51,797,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,254 | cpp | #include "Pair.h"
Pair::Pair(char val1, char val2){
// Set the pieces at their starting locations
p1.location.x = X_START;
p1.location.y = Y_START;
p1.value = val1;
p2.location.x = X_START;
p2.location.y = Y_START + 1;
p2.value = val2;
moving = true; // Set them movings
state = P_LEFT; // Where is the movable piece in respect to the pivot
}
/*
Copy constructor
*/
Pair::Pair(const Pair& p){
this->p1 = p.p1;
this->p2 = p.p2;
this->moving = p.moving;
}
Pair::~Pair(){
// Empty destructor
}
void Pair::Shift(){ // Left piece shifts, the other one stays as pivot
// p2 is the pivot, p1 moves
switch (state){
case P_LEFT:
if (p1.location.x < X_SIZE - 1){
// if p1 is at the left of p2
// AND it can be shifted
p1.old_location = p1.location;
p1.location.x++;
p1.location.y++;
state = P_DOWN;
}
break;
case P_DOWN:
if (p1.location.y < Y_SIZE - 1){
// If p1 is below p2, and it can be shifted
p1.old_location = p1.location;
p1.location.x--;
p1.location.y++;
state = P_RIGHT;
}
break;
case P_RIGHT:
if (p1.location.x > 0){
// If p1 is to the right of p2, and it can be shifted
p1.old_location = p1.location;
p1.location.x--;
p1.location.y--;
state = P_UP;
}
break;
case P_UP:
if (p1.location.y > 0){
// If p1 is above p2 and can be shifted
p1.old_location = p1.location;
p1.location.x++;
p1.location.y--;
state = P_LEFT;
}
break;
}
}
// Move the pair in a given direction
void Pair::Move(int direction){
switch (direction){
case DOWN:
default:
if (p1.location.x < X_SIZE && p2.location.x < X_SIZE){
p1.old_location = p1.location;
p2.old_location = p2.location;
p1.location.x++;
p2.location.x++;
}
break;
case LEFT:
if (p1.location.y > 0 && p2.location.y > 0){
p1.old_location = p1.location;
p2.old_location = p2.location;
p1.location.y--;
p2.location.y--;
}
break;
case RIGHT:
if (p1.location.y < Y_SIZE && p2.location.y < Y_SIZE){
p1.old_location = p1.location;
p2.old_location = p2.location;
p1.location.y++;
p2.location.y++;
}
break;
}
}
// These methods are explained at Pair.h
Piece Pair::getLowest(bool* both){
if (p1.location.x == p2.location.x){
*both = true;
return p2;
}
if (p1.location.x < p2.location.x){
*both = false;
return p2;
}
if (p1.location.x > p2.location.x) {
*both = false;
return p1;
}
}
Piece Pair::getLeftMost(bool* both){
if (p1.location.y == p2.location.y){
*both = true;
return p2;
}
if (p1.location.y < p2.location.y){
*both = false;
return p1;
}
if (p1.location.y > p2.location.y){
*both = false;
return p2;
}
}
Piece Pair::getRightMost(bool* both){
if (p1.location.y == p2.location.y){
*both = true;
return p2;
}
if (p1.location.y < p2.location.y){
*both = false;
return p2;
}
if (p1.location.y > p2.location.y){
*both = false;
return p1;
}
}
// To change the values of the pieces
void Pair::ChangeP1OldLocation(Location newLoc){
p1.old_location = newLoc;
}
void Pair::ChangeP1Location(Location newLoc){
p1.location = newLoc;
}
void Pair::ChangePivotOldLocation(Location newLoc){
p2.old_location = newLoc;
}
void Pair::ChangePivotLocation(Location newLoc){
p2.location = newLoc;
}
| [
"darth_carlos_90@hotmail.com"
] | darth_carlos_90@hotmail.com |
be8c4aac6886e29a8c0aaca7199588312a0948ac | bf7cf4c0f777dc3648be7831bb4f05793cd2cf8d | /OOP_Week09/MonsterWorld3/MonsterWorldGame.cpp | a17b1259e6da18ba92c4825259cacaa833b82022 | [] | no_license | aCordion/CK_2018-01-02 | c846ca48ea2599f343046cedb454f60709d02b9d | 7bb2c8448b10e1fccd4a06ae4489f523b0b25821 | refs/heads/master | 2021-08-22T15:31:39.403543 | 2018-12-19T11:12:32 | 2018-12-19T11:12:32 | 148,662,280 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 1,298 | cpp | #include "MonsterWorld.h"
#include "VariousMonsters.h"
#include <time.h>
void main() {
srand((unsigned int)time(NULL));
int w = 16, h = 8;
CMonsterWorld game(w, h);
{
// CMonster m("몬스터", "※", rand() % w, rand() % h);
// game.add(m);
/*
game.add(CMonster("몬스터", "※", rand() % w, rand() % h));
game.add(CMonster("도깨비", "§", rand() % w, rand() % h));
game.add(CMonster("별그대", "★", rand() % w, rand() % h));
game.add(CMonster("고스트", "♥", rand() % w, rand() % h));
*/
}
{
/*
game.add(new CMonster("몬스터", "※", rand() % w, rand() % h));
game.add(new CMonster("도깨비", "§", rand() % w, rand() % h));
game.add(new CMonster("별그대", "★", rand() % w, rand() % h));
game.add(new CMonster("고스트", "♥", rand() % w, rand() % h));
*/
}
{
game.add(new Zombie("허접한좀비", "§", rand() % w, rand() % h));
game.add(new Vampire("뱀파이어짱", "★", rand() % w, rand() % h));
game.add(new KGhost("어쩌다귀신", "♥", rand() % w, rand() % h));
game.add(new Jiangshi("못먹어도고", "↔", rand() % w, rand() % h, true));
game.add(new Jiangshi("못먹어세로", "↕", rand() % w, rand() % h, false));
}
game.play(500, 500);
printf("------게임 종료-------------------\n");
} | [
"39215817+aCordion@users.noreply.github.com"
] | 39215817+aCordion@users.noreply.github.com |
adcc2cf420e02bc65183add9acedfb241af41495 | d4100eddb658f1dadc262e7ee4f996bafed87160 | /src/engine/components/modelcomponent.hpp | 378a2772d3970edc784ca807106f79753e829eb5 | [] | no_license | MrDanTheMan/labour-day | be851db78069f02d9e4eaa0b1d2e5c535d5499e2 | f0fb0662fa246db19922d86ec5ca1fd1238221a5 | refs/heads/master | 2021-06-25T13:51:05.113118 | 2020-11-18T01:47:36 | 2020-11-18T01:47:36 | 213,165,982 | 0 | 0 | null | 2020-11-18T01:47:37 | 2019-10-06T12:38:53 | C++ | UTF-8 | C++ | false | false | 1,186 | hpp | #ifndef MODEL_COMPONENT_HPP_
#define MODEL_COMPONENT_HPP_
#include "../entity.hpp"
#include "../entityserialiser.hpp"
#include "../model.hpp"
#include "../renderable.hpp"
namespace Engine::Components
{
class ModelComponentSerialiser : public EntityComponentSerialiser
{
public:
ModelComponentSerialiser();
virtual ~ModelComponentSerialiser();
virtual bool Deserialise(EntityComponent* pComponent, const ContentEntityComponentInfo * pComponentInfo) const override;
virtual bool DeserialiseAdd(Entity* pEntity, const ContentEntityComponentInfo * pComponentInfo) const override;
};
class ModelComponent: public EntityComponent
{
public:
ModelComponent();
ModelComponent(const ModelComponent &rhs);
virtual ~ModelComponent();
virtual void Init() override;
virtual std::unique_ptr<Engine::EntityComponent> Duplicate() const override;
void SetModel(Model * const model);
Model* const ModelHandle() const;
Renderable* const GetRenderable() const;
public:
std::string m_modelName;
private:
Model *m_model;
};
}
#endif | [
"dantheman.py@gmail.com"
] | dantheman.py@gmail.com |
964512eafeb186153e5921115ea5e658fe327db8 | 665cb612224888dfd82f9f11da5416c3e2c09fd1 | /src/game/ConsoleLogListener.cpp | 6fda80d464bf2773fde7b8ff1a9cf71b4d00eefe | [
"Unlicense"
] | permissive | amarsero/stridecpp | 8627003bcede7035bb77453230594eeb57b3b273 | afc37c50c735d59a4e0784787f3c905ff98e3f66 | refs/heads/main | 2023-06-15T09:15:57.604677 | 2021-07-10T22:55:45 | 2021-07-10T22:55:45 | 384,563,057 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,019 | cpp | #include "ConsoleLogListener.h"
inline void ConsoleLogListener::OnLog(ILogMessage logMessage)
{
static const char * const debug = "\x1B[30m";
static const char * const verbose = "\x1B[30m";
static const char * const info = "\x1B[90m";
static const char * const warning = "\x1B[33m";
static const char * const error = "\x1B[31m";
static const char * const fatal = "\033[1;37;91m";
static const char * const colorSuffix = "\033[0m";
const char *color = NULL;
switch (logMessage.Type) {
case LogMessageType::Debug:
color = debug;
break;
case LogMessageType::Verbose:
color = verbose;
break;
case LogMessageType::Info:
color = info;
break;
case LogMessageType::Warning:
color = warning;
break;
case LogMessageType::Error:
color = error;
break;
case LogMessageType::Fatal:
color = fatal;
break;
default:
color = info;
break;
}
printf("%s%s%s\n", color, logMessage.Text.c_str(), colorSuffix);
}
| [
"amarsero@gmail.com"
] | amarsero@gmail.com |
6629c3bcc9a26bb9015972c026206dfd5dddb133 | a33aac97878b2cb15677be26e308cbc46e2862d2 | /program_data/PKU_raw/14/956.c | 289c14991c15891b34a4238ad380aa2330f8d034 | [] | no_license | GabeOchieng/ggnn.tensorflow | f5d7d0bca52258336fc12c9de6ae38223f28f786 | 7c62c0e8427bea6c8bec2cebf157b6f1ea70a213 | refs/heads/master | 2022-05-30T11:17:42.278048 | 2020-05-02T11:33:31 | 2020-05-02T11:33:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,006 | c | struct Student
{
long id;
int chn;
int mth;
int total;
struct Student *next;
};
struct Student * insert(struct Student *head,struct Student *stu)
{
int j=0;
struct Student *p0,*p1,*p2;
p1=head;
p0=stu;
if(head==NULL)
{head=p0;p0->next=NULL;}
else
{
while((p0->total<=p1->total)&&(p1->next!=NULL)&&j<4)
{p2=p1;p1=p1->next;j++;}
if(p0->total>p1->total)
{
if(head==p1) head=p0;
else p2->next=p0;
p0->next=p1;
}
else
{p1->next=p0;p0->next=NULL;}
}
return(head);
}
void main()
{
struct Student *p1,*head,*stu;
long int i,n;
scanf("%ld",&n);
p1=head=(struct Student*)malloc(sizeof(struct Student));
scanf("%d %d %d",&head->id,&head->chn,&head->mth);
head->total=head->chn + head->mth;
head->next=NULL;
for(i=1;i<n;i++)
{
stu=(struct Student*)malloc(sizeof(struct Student));
scanf("%d %d %d",&stu->id,&stu->chn,&stu->mth);
stu->total=stu->chn + stu->mth;
head=insert(head,stu);
}
p1=head;
for(i=0;i<3;i++)
{printf("%d %d\n",p1->id,p1->total);p1=p1->next;}
} | [
"bdqnghi@gmail.com"
] | bdqnghi@gmail.com |
f11f2b85581ce9a7b4c2f838d6c5e4df0aaf6b66 | 30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a | /contest/1542502252.cpp | 7211c065461ff4b179116c7bd4df1356b08de8aa | [] | no_license | thegamer1907/Code_Analysis | 0a2bb97a9fb5faf01d983c223d9715eb419b7519 | 48079e399321b585efc8a2c6a84c25e2e7a22a61 | refs/heads/master | 2020-05-27T01:20:55.921937 | 2019-11-20T11:15:11 | 2019-11-20T11:15:11 | 188,403,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 956 | cpp | #pragma GCC optimize(2)
#include<cstdio>
#include<cstring>
#define RG register
#define R RG int
#define G c=getchar()
typedef long long LL;
const int N=1e5+9;
int a[N],c[N];
LL ff[N],gg[N],*f=ff,*g=gg;
inline int in(){
RG char G;
while(c<'-')G;
R x=c&15;G;
while(c>'-')x=x*10+(c&15),G;
return x;
}
void solve(R l,R r,R kl,R kr,RG LL w){
if(l>r)return;
R m=(l+r)>>1,k=0,p=m<kr?m:kr,i;
for(i= l;i<=m;++i)w+=c[a[i]]++;
for(i=kl;i<=p;++i)w-=--c[a[i]],g[m]>f[i]+w?g[m]=f[i]+w,k=i:0;
for(i=kl;i<=p;++i)w+=c[a[i]]++;
for(i= l;i<=m;++i)w-=--c[a[i]];
solve(l,m-1,kl,k,w);
for(i= l;i<=m;++i)w+=c[a[i]]++;
for(i=kl;i< k;++i)w-=--c[a[i]];
solve(m+1,r,k,kr,w);
for(i=kl;i< k;++i)++c[a[i]];
for(i= l;i<=m;++i)--c[a[i]];
}
int main(){
R n=in(),k=in();
RG LL*tmp;
for(R i=1;i<=n;++i)
f[i]=f[i-1]+c[a[i]=in()]++;
memset(c,0,(n+1)<<2);
while(--k){
memset(g,1,(n+1)<<3);
solve(1,n,1,n,0);
tmp=f;f=g;g=tmp;
}
printf("%lld\n",f[n]);
return 0;
} | [
"harshitagar1907@gmail.com"
] | harshitagar1907@gmail.com |
6a44f7d97e9ed05d97055278cd39fa5a55814524 | 6e7140b7d68df7b41490216b303c73491e5e8021 | /PhysiCell_Performance_Test/core/PhysiCell_phenotype.cpp | 5edfb111488c9a4fb31f8e2c399f3578ce9035b2 | [] | no_license | furkankurtoglu/PhysiCell-SBML-trials | ff328460a732504155a193a27bdf4f5b0ff91c53 | 02cdfb8b9ebc210029083e7d2c26eb1582728ec8 | refs/heads/master | 2022-03-21T19:42:21.332782 | 2022-03-05T16:37:29 | 2022-03-05T16:37:29 | 243,384,961 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,314 | cpp | /*
###############################################################################
# If you use PhysiCell in your project, please cite PhysiCell and the version #
# number, such as below: #
# #
# We implemented and solved the model using PhysiCell (Version x.y.z) [1]. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018 #
# DOI: 10.1371/journal.pcbi.1005991 #
# #
# See VERSION.txt or call get_PhysiCell_version() to get the current version #
# x.y.z. Call display_citations() to get detailed information on all cite-#
# able software used in your PhysiCell application. #
# #
# Because PhysiCell extensively uses BioFVM, we suggest you also cite BioFVM #
# as below: #
# #
# We implemented and solved the model using PhysiCell (Version x.y.z) [1], #
# with BioFVM [2] to solve the transport equations. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018 #
# DOI: 10.1371/journal.pcbi.1005991 #
# #
# [2] A Ghaffarizadeh, SH Friedman, and P Macklin, BioFVM: an efficient para- #
# llelized diffusive transport solver for 3-D biological simulations, #
# Bioinformatics 32(8): 1256-8, 2016. DOI: 10.1093/bioinformatics/btv730 #
# #
###############################################################################
# #
# BSD 3-Clause License (see https://opensource.org/licenses/BSD-3-Clause) #
# #
# Copyright (c) 2015-2018, Paul Macklin and the PhysiCell Project #
# All rights reserved. #
# #
# Redistribution and use in source and binary forms, with or without #
# modification, are permitted provided that the following conditions are met: #
# #
# 1. Redistributions of source code must retain the above copyright notice, #
# this list of conditions and the following disclaimer. #
# #
# 2. Redistributions in binary form must reproduce the above copyright #
# notice, this list of conditions and the following disclaimer in the #
# documentation and/or other materials provided with the distribution. #
# #
# 3. Neither the name of the copyright holder nor the names of its #
# contributors may be used to endorse or promote products derived from this #
# software without specific prior written permission. #
# #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE #
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #
# POSSIBILITY OF SUCH DAMAGE. #
# #
###############################################################################
*/
#include "./PhysiCell_phenotype.h"
#include "../BioFVM/BioFVM.h"
#include "./PhysiCell_constants.h"
#include "./PhysiCell_utilities.h"
using namespace BioFVM;
namespace PhysiCell{
Phase::Phase()
{
index = 0;
code = 0;
name = "unnamed";
division_at_phase_exit = false;
removal_at_phase_exit = false;
entry_function = NULL;
return;
}
Phase_Link::Phase_Link()
{
start_phase_index = 0;
end_phase_index = 0;
fixed_duration = false;
arrest_function = NULL;
exit_function = NULL;
return;
}
Cycle_Data::Cycle_Data()
{
inverse_index_maps.resize(0);
pCycle_Model = NULL;
time_units = "min";
transition_rates.resize( 0 );
current_phase_index = 0;
elapsed_time_in_phase = 0.0;
return;
}
void Cycle_Data::sync_to_cycle_model( void )
{
// make sure the inverse map is the right size
int n = pCycle_Model->phases.size();
inverse_index_maps.resize( n );
// sync the inverse map to the cell cycle model by
// querying the phase_links
transition_rates.resize( n );
// also make sure the transition_rates[] are the right size
for( int i=0 ; i < pCycle_Model->phase_links.size() ; i++ )
{
inverse_index_maps[i].clear();
for( int j=0 ; j < pCycle_Model->phase_links[i].size() ; j++ )
{
inverse_index_maps[i][ pCycle_Model->phase_links[i][j].end_phase_index ] = j;
transition_rates[i].resize( pCycle_Model->phase_links[i].size() );
}
}
return;
}
double& Cycle_Data::transition_rate( int start_phase_index , int end_phase_index )
{
return transition_rates[ start_phase_index ][ inverse_index_maps[start_phase_index][end_phase_index] ];
}
double& Cycle_Data::exit_rate(int phase_index )
{
return transition_rates[phase_index][0];
}
Cycle_Model::Cycle_Model()
{
inverse_index_maps.resize( 0 );
name = "unnamed";
phases.resize(0);
phase_links.resize(0);
data.pCycle_Model = this;
code = PhysiCell_constants::custom_cycle_model;
default_phase_index = 0;
return;
}
int Cycle_Model::add_phase( int code, std::string name )
{
int n = phases.size();
// resize the data structures
phases.resize( n+1 );
phase_links.resize( n+1 );
phase_links[n].resize(0);
inverse_index_maps.resize( n+1 );
inverse_index_maps[n].clear();
// update phase n
phases[n].code = code;
phases[n].index = n;
phases[n].name.assign( name );
// make sure the cycle_data is also correctly sized
data.sync_to_cycle_model();
return n;
}
int Cycle_Model::add_phase_link( int start_index, int end_index ,
bool (*arrest_function)(Cell* pCell, Phenotype& phenotype, double dt) )
{
// first, resize the phase links
int n = phase_links[start_index].size();
phase_links[start_index].resize( n + 1 );
// now, update the new phase links
phase_links[start_index][n].start_phase_index = start_index;
phase_links[start_index][n].end_phase_index = end_index;
phase_links[start_index][n].arrest_function = arrest_function;
// now, update the inverse index map
inverse_index_maps[start_index][end_index] = n;
// lastly, make sure the transition rates are the right size;
data.sync_to_cycle_model();
return n;
}
int Cycle_Model::add_phase_link( int start_index, int end_index , double rate ,
bool (*arrest_function)(Cell* pCell, Phenotype& phenotype, double dt) )
{
int n = add_phase_link( start_index , end_index , arrest_function );
data.transition_rate( start_index , end_index ) = rate;
return n;
}
int Cycle_Model::find_phase_index( int code )
{
for( int i=0 ; i < phases.size() ; i++ )
{
if( phases[i].code == code )
{ return i; }
}
return 0;
}
int Cycle_Model::find_phase_index( std::string name )
{
for( int i=0 ; i < phases.size() ; i++ )
{
if( phases[i].name == name )
{ return i; }
}
return 0;
}
std::ostream& Cycle_Model::display( std::ostream& os )
{
os << "Cycle Model: " << name << " (PhysiCell code: " << code << ")" << std::endl;
os << "Phases and links: (* denotes phase with cell division)" << std::endl;
for( int i=0; i < phases.size() ; i++ )
{
os << "Phase " << i << " (" << phases[i].name << ") ";
if( phases[i].division_at_phase_exit )
{ os << "*"; }
os << " links to: " << std::endl;
for( int k=0 ; k < phase_links[i].size() ; k++ )
{
int j = phase_links[i][k].end_phase_index;
os << "\tPhase " << j << " (" << phases[j].name << ") with rate " << data.transition_rate(i,j) << " " << data.time_units << "^-1; " << std::endl;
}
os << std::endl;
}
return os;
}
double& Cycle_Model::transition_rate( int start_index , int end_index )
{
return data.transition_rate( start_index , end_index );
}
Phase_Link& Cycle_Model::phase_link( int start_index, int end_index )
{
return phase_links[start_index][ inverse_index_maps[start_index][end_index] ];
}
void Cycle_Model::advance_model( Cell* pCell, Phenotype& phenotype, double dt )
{
int i = phenotype.cycle.data.current_phase_index;
phenotype.cycle.data.elapsed_time_in_phase += dt;
// Evaluate each linked phase:
// advance to that phase IF probabiltiy is in the range,
// and if the arrest function (if any) is false
int j;
for( int k=0 ; k < phase_links[i].size() ; k++ )
{
j = phase_links[i][k].end_phase_index;
// check for arrest. If arrested, skip to the next transition
bool transition_arrested = false;
if( phase_links[i][k].arrest_function )
{
transition_arrested = phase_links[i][k].arrest_function( pCell,phenotype,dt );
}
if( !transition_arrested )
{
// check to see if we should transition
bool continue_transition = false;
if( phase_links[i][k].fixed_duration )
{
if( phenotype.cycle.data.elapsed_time_in_phase > 1.0/phenotype.cycle.data.transition_rates[i][k] )
{
continue_transition = true;
}
}
else
{
double prob = phenotype.cycle.data.transition_rates[i][k]*dt;
if( UniformRandom() <= prob )
{
continue_transition = true;
}
}
// if we should transition, check if we're not supposed to divide or die
if( continue_transition )
{
// if the phase transition has an exit function, execute it
if( phase_links[i][k].exit_function )
{
phase_links[i][k].exit_function( pCell,phenotype,dt );
}
// check if division or removal are required
if( phases[i].division_at_phase_exit )
{
// pCell->flag_for_division();
phenotype.flagged_for_division = true;
}
if( phases[i].removal_at_phase_exit )
{
// pCell->flag_for_removal();
phenotype.flagged_for_removal = true;
return;
}
// move to the next phase, and reset the elapsed time
phenotype.cycle.data.current_phase_index = j;
phenotype.cycle.data.elapsed_time_in_phase = 0.0;
// if the new phase has an entry function, execute it
if( phases[j].entry_function )
{
phases[j].entry_function( pCell,phenotype,dt );
}
return;
}
}
}
return;
}
Phase& Cycle_Data::current_phase( void )
{
return pCycle_Model->phases[current_phase_index];
}
Death_Parameters::Death_Parameters()
{
time_units = "min";
// reference values: MCF-7 (1/min)
unlysed_fluid_change_rate = 3.0/60.0; // apoptosis
lysed_fluid_change_rate = 0.05/60.0; // lysed necrotic cell
cytoplasmic_biomass_change_rate = 1.0/60.0; // apoptosis
nuclear_biomass_change_rate = 0.35/60.0; // apoptosis
calcification_rate = 0.0; // 0.0042 for necrotic cells
relative_rupture_volume = 2.0;
return;
}
Death::Death()
{
rates.resize( 0 );
models.resize( 0 );
parameters.resize( 0 );
dead = false;
current_death_model_index = 0;
return;
}
int Death::add_death_model( double rate , Cycle_Model* pModel )
{
rates.push_back( rate );
models.push_back( pModel );
parameters.resize( rates.size() );
return rates.size() - 1;
}
int Death::add_death_model( double rate, Cycle_Model* pModel, Death_Parameters& death_parameters)
{
rates.push_back( rate );
models.push_back( pModel );
parameters.push_back( death_parameters );
return rates.size() - 1;
}
int Death::find_death_model_index( int code )
{
for( int i=0 ; i < models.size() ; i++ )
{
if( models[i]->code == code )
{ return i; }
}
return 0;
}
int Death::find_death_model_index( std::string name )
{
for( int i=0 ; i < models.size() ; i++ )
{
if( models[i]->name == name )
{ return i; }
}
return 0;
}
bool Death::check_for_death( double dt )
{
// If the cell is already dead, exit.
if( dead == true )
{
return false;
}
// If the cell is alive, evaluate all the
// death rates for each registered death type.
int i = 0;
while( !dead && i < rates.size() )
{
if( UniformRandom() < rates[i]*dt )
{
// update the Death data structure
dead = true;
current_death_model_index = i;
// and set the cycle model to this death model
return dead;
}
i++;
}
return dead;
}
void Death::trigger_death( int death_model_index )
{
dead = true;
current_death_model_index = death_model_index;
/*
// if so, change the cycle model to the current death model
phenotype.cycle.sync_to_cycle_model( phenotype.death.current_model() );
// also, turn off motility.
phenotype.motility.is_motile = false;
phenotype.motility.motility_vector.assign( 3, 0.0 );
functions.update_migration_bias = NULL;
// turn off secretion, and reduce uptake by a factor of 10
phenotype.secretion.set_all_secretion_to_zero();
phenotype.secretion.scale_all_uptake_by_factor( 0.10 );
// make sure to run the death entry function
if( phenotype.cycle.current_phase().entry_function )
{
phenotype.cycle.current_phase().entry_function( this, phenotype, dt_ );
}
*/
return;
}
Cycle_Model& Death::current_model( void )
{
return *models[current_death_model_index];
}
Cycle::Cycle()
{
pCycle_Model = NULL;
return;
}
void Cycle::advance_cycle( Cell* pCell, Phenotype& phenotype, double dt )
{
pCycle_Model->advance_model( pCell, phenotype , dt );
return;
}
Cycle_Model& Cycle::model( void )
{
return *pCycle_Model;
}
Phase& Cycle::current_phase( void )
{
return data.current_phase();
}
int& Cycle::current_phase_index( void )
{
return data.current_phase_index;
}
void Cycle::sync_to_cycle_model( Cycle_Model& cm )
{
pCycle_Model = &cm;
data = cm.data;
return;
}
Death_Parameters& Death::current_parameters( void )
{
return parameters[ current_death_model_index ];
}
Volume::Volume()
{
// reference parameter values for MCF-7, in cubic microns
fluid_fraction = 0.75;
total = 2494;
fluid = fluid_fraction * total;
solid = total-fluid;
nuclear = 540.0;
nuclear_fluid = fluid_fraction * nuclear;
nuclear_solid = nuclear - nuclear_fluid;
cytoplasmic = total - nuclear;
cytoplasmic_fluid = fluid_fraction*cytoplasmic;
cytoplasmic_solid = cytoplasmic - cytoplasmic_fluid;
// rates are in units of 1/min
cytoplasmic_biomass_change_rate = 0.27 / 60.0;
nuclear_biomass_change_rate = 0.33 / 60.0;
fluid_change_rate = 3.0 / 60.0;
calcified_fraction = 0.0;
calcification_rate = 0.0;
target_solid_cytoplasmic = cytoplasmic_solid;
target_solid_nuclear = nuclear_solid;
target_fluid_fraction = fluid_fraction;
cytoplasmic_to_nuclear_ratio = cytoplasmic / ( 1e-16 + nuclear);
target_cytoplasmic_to_nuclear_ratio = cytoplasmic_to_nuclear_ratio;
// the cell bursts at these volumes
relative_rupture_volume = 2.0;
// as fraction of volume at entry to the current phase
rupture_volume = relative_rupture_volume * total; // in volume units
return;
};
void Volume::multiply_by_ratio( double ratio )
{
total *= ratio;
solid *= ratio;
fluid *= ratio;
nuclear *= ratio;
nuclear_fluid *= ratio;
nuclear_solid *= ratio;
cytoplasmic *= ratio;
cytoplasmic_fluid *= ratio;
cytoplasmic_solid *= ratio;
rupture_volume *= ratio;
target_solid_nuclear *= ratio;
target_solid_cytoplasmic *= ratio;
return;
}
void Volume::divide( void )
{
multiply_by_ratio( 0.5 );
return;
}
Geometry::Geometry()
{
// reference values for MCF-7, based on
// volume = 2494 cubic microns
// nuclear volume = 540 cubic microns
radius = 8.412710547954228;
nuclear_radius = 5.051670902881889;
surface_area = 889.3685284131693;
polarity = 0.0;
return;
}
void Geometry::update_radius( Cell* pCell, Phenotype& phenotype, double dt )
{
static double four_thirds_pi = 4.188790204786391;
radius = phenotype.volume.total;
radius /= four_thirds_pi;
radius = pow( radius , 0.333333333333333333333333333333333333333 );
return;
}
void Geometry::update_nuclear_radius( Cell* pCell, Phenotype& phenotype, double dt )
{
static double four_thirds_pi = 4.188790204786391;
nuclear_radius = phenotype.volume.nuclear;
nuclear_radius /= four_thirds_pi;
nuclear_radius = pow( nuclear_radius , 0.333333333333333333333333333333333333333 );
return;
}
void Geometry::update_surface_area( Cell* pCell, Phenotype& phenotype, double dt )
{
// 4pi / (4pi/3)^(2/3)
static double the_constant = 4.835975862049409;
surface_area = pow( phenotype.volume.total , 0.666666666666667 );
surface_area /= the_constant;
return;
}
void Geometry::update( Cell* pCell, Phenotype& phenotype, double dt )
{
update_radius(pCell,phenotype,dt);
update_nuclear_radius(pCell,phenotype,dt);
// surface area = 4*pi*r^2 = (4/3)*pi*r^3 / (r/3)
surface_area = phenotype.volume.total;
surface_area /= radius;
surface_area *= 3.0;
return;
}
Mechanics::Mechanics()
{
cell_cell_adhesion_strength = 0.4;
cell_BM_adhesion_strength = 4.0;
cell_cell_repulsion_strength = 10.0;
cell_BM_repulsion_strength = 10.0;
// this is a multiple of the cell (equivalent) radius
relative_maximum_adhesion_distance = 1.25;
// maximum_adhesion_distance = 0.0;
return;
}
// new on July 29, 2018
// change the ratio without changing the repulsion strength or equilibrium spacing
void Mechanics::set_relative_maximum_adhesion_distance( double new_value )
{
// get old equilibrium spacing, based on equilibriation of pairwise adhesive/repulsive forces at that distance.
// relative equilibrium spacing (relative to mean cell radius)
double s_relative = 2.0;
double temp1 = cell_cell_adhesion_strength;
temp1 /= cell_cell_repulsion_strength;
temp1 = sqrt( temp1 );
double temp2 = 1.0;
temp2 -= temp1; // 1 - sqrt( alpha_CCA / alpha_CCR );
s_relative *= temp2; // 2*( 1 - sqrt( alpha_CCA / alpha_CCR ) );
temp1 /= relative_maximum_adhesion_distance; // sqrt( alpha_CCA / alpha_CCR)/f;
temp2 = 1.0;
temp2 -= temp1; // 1 - sqrt( alpha_CCA / alpha_CCR )/f;
s_relative /= temp2; // 2*( 1 - sqrt( alpha_CCA / alpha_CCR ) ) / ( 1-1/f) ;
// now, adjust the relative max adhesion distance
relative_maximum_adhesion_distance = new_value;
// adjust the adhesive coefficient to preserve the old equilibrium distance
temp1 = s_relative;
temp1 /= 2.0;
temp2 = 1.0;
temp2 -= temp1; // 1 - s_relative/2.0
temp1 /= relative_maximum_adhesion_distance; // s_relative/(2*relative_maximum_adhesion_distance);
temp1 *= -1.0; // -s_relative/(2*relative_maximum_adhesion_distance);
temp1 += 1.0; // 1.0 -s_relative/(2*relative_maximum_adhesion_distance);
temp2 /= temp1;
temp2 *= temp2;
cell_cell_adhesion_strength = cell_cell_repulsion_strength;
cell_cell_adhesion_strength *= temp2;
return;
}
// new on July 29, 2018
// set the cell-cell equilibrium spacing, accomplished by changing the
// cell-cell adhesion strength, while leaving the cell-cell repulsion
// strength and the maximum adhesion distance unchanged
void Mechanics::set_relative_equilibrium_distance( double new_value )
{
if( new_value > 2.0 )
{
std::cout << "**** Warning in function " << __FUNCTION__ << " in " << __FILE__ << " : " << std::endl
<< "\tAttempted to set equilibrium distance exceeding two cell radii." << std::endl
<< "\tWe will cap the equilibrium distance at 2.0 cell radii." << std::endl
<< "****" << std::endl << std::endl;
new_value = 2.0;
}
// adjust the adhesive coefficient to achieve the new (relative) equilibrium distance
double temp1 = new_value;
temp1 /= 2.0;
double temp2 = 1.0;
temp2 -= temp1; // 1 - s_relative/2.0
temp1 /= relative_maximum_adhesion_distance; // s_relative/(2*relative_maximum_adhesion_distance);
temp1 *= -1.0; // -s_relative/(2*relative_maximum_adhesion_distance);
temp1 += 1.0; // 1.0 -s_relative/(2*relative_maximum_adhesion_distance);
temp2 /= temp1;
temp2 *= temp2;
cell_cell_adhesion_strength = cell_cell_repulsion_strength;
cell_cell_adhesion_strength *= temp2;
return;
}
void Mechanics::set_absolute_equilibrium_distance( Phenotype& phenotype, double new_value )
{
return set_relative_equilibrium_distance( new_value / phenotype.geometry.radius );
}
// void Mechanics::set_absolute_maximum_adhesion_distance( double new_value );
// void
Motility::Motility()
{
is_motile = false;
persistence_time = 1.0;
migration_speed = 1.0;
migration_bias_direction.resize( 3 , 0.0 );
migration_bias = 0.0;
restrict_to_2D = false;
// update_migration_bias_direction = NULL;
motility_vector.resize( 3 , 0.0 );
chemotaxis_index = 0;
chemotaxis_direction = 1;
return;
}
Secretion::Secretion()
{
pMicroenvironment = get_default_microenvironment();
sync_to_current_microenvironment();
return;
}
void Secretion::sync_to_current_microenvironment( void )
{
if( pMicroenvironment )
{
sync_to_microenvironment( pMicroenvironment );
}
else
{
secretion_rates.resize( 0 , 0.0 );
uptake_rates.resize( 0 , 0.0 );
saturation_densities.resize( 0 , 0.0 );
net_export_rates.resize( 0, 0.0 );
}
return;
}
void Secretion::sync_to_microenvironment( Microenvironment* pNew_Microenvironment )
{
pMicroenvironment = pNew_Microenvironment;
secretion_rates.resize( pMicroenvironment->number_of_densities() , 0.0 );
uptake_rates.resize( pMicroenvironment->number_of_densities() , 0.0 );
saturation_densities.resize( pMicroenvironment->number_of_densities() , 0.0 );
net_export_rates.resize( pMicroenvironment->number_of_densities() , 0.0 );
return;
}
void Secretion::advance( Basic_Agent* pCell, Phenotype& phenotype , double dt )
{
// if this phenotype is not associated with a cell, exit
if( pCell == NULL )
{ return; }
// if there is no microenvironment, attempt to sync.
if( pMicroenvironment == NULL )
{
// first, try the cell's microenvironment
if( pCell->get_microenvironment() )
{
sync_to_microenvironment( pCell->get_microenvironment() );
}
// otherwise, try the default microenvironment
else
{
sync_to_microenvironment( get_default_microenvironment() );
}
// if we've still failed, return.
if( pMicroenvironment == NULL )
{
return;
}
}
// make sure the associated cell has the correct rate vectors
if( pCell->secretion_rates != &secretion_rates )
{
delete pCell->secretion_rates;
delete pCell->uptake_rates;
delete pCell->saturation_densities;
delete pCell->net_export_rates;
pCell->secretion_rates = &secretion_rates;
pCell->uptake_rates = &uptake_rates;
pCell->saturation_densities = &saturation_densities;
pCell->net_export_rates = &net_export_rates;
pCell->set_total_volume( phenotype.volume.total );
pCell->set_internal_uptake_constants( dt );
}
// now, call the BioFVM secretion/uptake function
pCell->simulate_secretion_and_uptake( pMicroenvironment , dt );
return;
}
void Secretion::set_all_secretion_to_zero( void )
{
for( int i=0; i < secretion_rates.size(); i++ )
{
secretion_rates[i] = 0.0;
net_export_rates[i] = 0.0;
}
return;
}
void Secretion::set_all_uptake_to_zero( void )
{
for( int i=0; i < uptake_rates.size(); i++ )
{ uptake_rates[i] = 0.0; }
return;
}
void Secretion::scale_all_secretion_by_factor( double factor )
{
for( int i=0; i < secretion_rates.size(); i++ )
{
secretion_rates[i] *= factor;
net_export_rates[i] *= factor;
}
return;
}
void Secretion::scale_all_uptake_by_factor( double factor )
{
for( int i=0; i < uptake_rates.size(); i++ )
{ uptake_rates[i] *= factor; }
return;
}
Molecular::Molecular()
{
pMicroenvironment = get_default_microenvironment();
sync_to_current_microenvironment();
return;
}
void Molecular::sync_to_current_microenvironment( void )
{
if( pMicroenvironment )
{
sync_to_microenvironment( pMicroenvironment );
}
else
{
internalized_total_substrates.resize( 0 , 0.0 );
fraction_released_at_death.resize( 0 , 0.0 );
fraction_transferred_when_ingested.resize( 0, 0.0 );
}
return;
}
void Molecular::sync_to_microenvironment( Microenvironment* pNew_Microenvironment )
{
pMicroenvironment = pNew_Microenvironment;
int number_of_densities = pMicroenvironment->number_of_densities() ;
internalized_total_substrates.resize( number_of_densities , 0.0 );
fraction_released_at_death.resize( number_of_densities , 0.0 );
fraction_transferred_when_ingested.resize( number_of_densities , 0.0 );
return;
}
void Molecular::sync_to_cell( Basic_Agent* pCell )
{
delete pCell->internalized_substrates;
pCell->internalized_substrates = &internalized_total_substrates;
delete pCell->fraction_released_at_death;
pCell->fraction_released_at_death = &fraction_released_at_death;
delete pCell->fraction_transferred_when_ingested;
pCell->fraction_transferred_when_ingested = &fraction_transferred_when_ingested;
return;
}
/*
void Molecular::advance( Basic_Agent* pCell, Phenotype& phenotype , double dt )
{
// if this phenotype is not associated with a cell, exit
if( pCell == NULL )
{ return; }
// if there is no microenvironment, attempt to sync.
if( pMicroenvironment == NULL )
{
// first, try the cell's microenvironment
if( pCell->get_microenvironment() )
{
sync_to_microenvironment( pCell->get_microenvironment() );
}
// otherwise, try the default microenvironment
else
{
sync_to_microenvironment( get_default_microenvironment() );
}
// if we've still failed, return.
if( pMicroenvironment == NULL )
{
return;
}
}
// make sure the associated cell has the correct rate vectors
if( pCell->internalized_substrates != &internalized_substrates )
{
// copy the data over
internalized_substrates = *(pCell->internalized_substrates);
// remove the BioFVM copy
delete pCell->internalized_substrates;
// point BioFVM to this one
pCell->internalized_substrates = &internalized_substrates;
}
// now, call the functions
// if( pCell->functions.internal_substrate_function )
// { pCell->functions.internal_substrate_function( pCell,phenotype,dt); }
// if( pCell->functions.molecular_model_function )
// { pCell->functions.molecular_model_function( pCell,phenotype,dt); }
return;
}
*/
Cell_Functions::Cell_Functions()
{
instantiate_cell = NULL;
volume_update_function = NULL;
update_migration_bias = NULL;
update_phenotype = NULL;
custom_cell_rule = NULL;
update_velocity = NULL;
add_cell_basement_membrane_interactions = NULL;
calculate_distance_to_membrane = NULL;
set_orientation = NULL;
contact_function = NULL;
custom_adhesion = NULL;
custom_repulsion = NULL;
/*
internal_substrate_function = NULL;
molecular_model_function = NULL;
*/
return;
}
void Phenotype::sync_to_functions( Cell_Functions& functions )
{
cycle.sync_to_cycle_model( functions.cycle_model );
return;
}
Phenotype::Phenotype()
{
flagged_for_division = false;
flagged_for_removal = false;
// sync the molecular stuff here automatically?
intracellular = NULL; //rwh: review
return;
}
void Phenotype::operator=(const Phenotype &p ) {
flagged_for_division = p.flagged_for_division;
flagged_for_removal = p.flagged_for_removal;
cycle = p.cycle;
death = p.death;
volume = p.volume;
geometry = p.geometry;
mechanics = p.mechanics;
motility = p.motility;
secretion = p.secretion;
molecular = p.molecular;
if (p.intracellular != NULL)
{
intracellular = p.intracellular->clone();
}
}
void Phenotype::operator=(Phenotype &p ) {
flagged_for_division = p.flagged_for_division;
flagged_for_removal = p.flagged_for_removal;
cycle = p.cycle;
death = p.death;
volume = p.volume;
geometry = p.geometry;
mechanics = p.mechanics;
motility = p.motility;
secretion = p.secretion;
molecular = p.molecular;
if (p.intracellular != NULL)
{
intracellular = p.intracellular->clone();
}
}
/*
class Bools
{
public:
std::vector<bool> values;
std::unordered_map<std::string,int> name_map;
std::string& name( int i );
std::vector<std::string> units;
void resize( int n );
int add( std::string name , std::string units , bool value );
bool& operator[]( int i );
bool& operator[]( std::string name );
Bools();
}
*/
Bools::Bools()
{
values.resize( 0 , true );
name_map.clear();
return;
}
int Bools::size( void )
{ return values.size(); }
void Phenotype::sync_to_microenvironment( Microenvironment* pMicroenvironment )
{
secretion.sync_to_microenvironment( pMicroenvironment );
molecular.sync_to_microenvironment( pMicroenvironment );
return;
}
};
| [
"fkurtog@iu.edu"
] | fkurtog@iu.edu |
f72fa3ea20f8edb2c3b492277e4daaf7ed332921 | 140d78334109e02590f04769ec154180b2eaf78d | /aws-cpp-sdk-application-autoscaling/source/model/ScalableTarget.cpp | ec0ebf9f2d53ef31651414331f5d0c27486b285e | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | coderTong/aws-sdk-cpp | da140feb7e5495366a8d2a6a02cf8b28ba820ff6 | 5cd0c0a03b667c5a0bd17394924abe73d4b3754a | refs/heads/master | 2021-07-08T07:04:40.181622 | 2017-08-22T21:50:00 | 2017-08-22T21:50:00 | 101,145,374 | 0 | 1 | Apache-2.0 | 2021-05-04T21:06:36 | 2017-08-23T06:24:37 | C++ | UTF-8 | C++ | false | false | 3,990 | cpp | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/application-autoscaling/model/ScalableTarget.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ApplicationAutoScaling
{
namespace Model
{
ScalableTarget::ScalableTarget() :
m_serviceNamespace(ServiceNamespace::NOT_SET),
m_serviceNamespaceHasBeenSet(false),
m_resourceIdHasBeenSet(false),
m_scalableDimension(ScalableDimension::NOT_SET),
m_scalableDimensionHasBeenSet(false),
m_minCapacity(0),
m_minCapacityHasBeenSet(false),
m_maxCapacity(0),
m_maxCapacityHasBeenSet(false),
m_roleARNHasBeenSet(false),
m_creationTimeHasBeenSet(false)
{
}
ScalableTarget::ScalableTarget(const JsonValue& jsonValue) :
m_serviceNamespace(ServiceNamespace::NOT_SET),
m_serviceNamespaceHasBeenSet(false),
m_resourceIdHasBeenSet(false),
m_scalableDimension(ScalableDimension::NOT_SET),
m_scalableDimensionHasBeenSet(false),
m_minCapacity(0),
m_minCapacityHasBeenSet(false),
m_maxCapacity(0),
m_maxCapacityHasBeenSet(false),
m_roleARNHasBeenSet(false),
m_creationTimeHasBeenSet(false)
{
*this = jsonValue;
}
ScalableTarget& ScalableTarget::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("ServiceNamespace"))
{
m_serviceNamespace = ServiceNamespaceMapper::GetServiceNamespaceForName(jsonValue.GetString("ServiceNamespace"));
m_serviceNamespaceHasBeenSet = true;
}
if(jsonValue.ValueExists("ResourceId"))
{
m_resourceId = jsonValue.GetString("ResourceId");
m_resourceIdHasBeenSet = true;
}
if(jsonValue.ValueExists("ScalableDimension"))
{
m_scalableDimension = ScalableDimensionMapper::GetScalableDimensionForName(jsonValue.GetString("ScalableDimension"));
m_scalableDimensionHasBeenSet = true;
}
if(jsonValue.ValueExists("MinCapacity"))
{
m_minCapacity = jsonValue.GetInteger("MinCapacity");
m_minCapacityHasBeenSet = true;
}
if(jsonValue.ValueExists("MaxCapacity"))
{
m_maxCapacity = jsonValue.GetInteger("MaxCapacity");
m_maxCapacityHasBeenSet = true;
}
if(jsonValue.ValueExists("RoleARN"))
{
m_roleARN = jsonValue.GetString("RoleARN");
m_roleARNHasBeenSet = true;
}
if(jsonValue.ValueExists("CreationTime"))
{
m_creationTime = jsonValue.GetDouble("CreationTime");
m_creationTimeHasBeenSet = true;
}
return *this;
}
JsonValue ScalableTarget::Jsonize() const
{
JsonValue payload;
if(m_serviceNamespaceHasBeenSet)
{
payload.WithString("ServiceNamespace", ServiceNamespaceMapper::GetNameForServiceNamespace(m_serviceNamespace));
}
if(m_resourceIdHasBeenSet)
{
payload.WithString("ResourceId", m_resourceId);
}
if(m_scalableDimensionHasBeenSet)
{
payload.WithString("ScalableDimension", ScalableDimensionMapper::GetNameForScalableDimension(m_scalableDimension));
}
if(m_minCapacityHasBeenSet)
{
payload.WithInteger("MinCapacity", m_minCapacity);
}
if(m_maxCapacityHasBeenSet)
{
payload.WithInteger("MaxCapacity", m_maxCapacity);
}
if(m_roleARNHasBeenSet)
{
payload.WithString("RoleARN", m_roleARN);
}
if(m_creationTimeHasBeenSet)
{
payload.WithDouble("CreationTime", m_creationTime.SecondsWithMSPrecision());
}
return payload;
}
} // namespace Model
} // namespace ApplicationAutoScaling
} // namespace Aws | [
"henso@amazon.com"
] | henso@amazon.com |
693d28c97fa8e4dd5016abe327e8a3b2aeffd6f1 | 4d33c090428407d599a4c0a586e0341353bcf8d7 | /trunk/tutorial/directx_16_terrainTextureLightingHardware/game.cpp | 968a39ae43a76a9e5a24e9ab2e33774882695837 | [] | no_license | yty/bud | f2c46d689be5dfca74e239f90570617b3471ea81 | a37348b77fb2722c73d972a77827056b0b2344f6 | refs/heads/master | 2020-12-11T06:07:55.915476 | 2012-07-22T21:48:05 | 2012-07-22T21:48:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,472 | cpp | #include "game.h"
//
#include "Modules.h"
//
#include "InputMessageHandler.h"
#include "render/Color.h"
//
WaitingForYou::WaitingForYou()
:_modules(NULL), _material(NULL), _vb(NULL), _fx(NULL), _camera(NULL), _cameraController(NULL), _modelMatrix(Mat4::IDENTITY), _texture(NULL), _vbInstances(NULL), _ib(NULL), _font(NULL)
,_vertexNumber(0), _mapWidth(0), _fx_axis(NULL)
{
_windowTitle = "tutorial";
}
WaitingForYou::~WaitingForYou()
{
}
bool WaitingForYou::createModules()
{
_modules = new Modules;
//
if (!_modules->create(_hwnd))
{
return false;
}
//
::ShowCursor(true);
//
return true;
}
bool WaitingForYou::foreRender()
{
//
return true;
}
bool WaitingForYou::rendering()
{
//
_modules->getRenderEngine()->getRenderSystem()->clear(0, NULL, Euclid::eClearFlags_Target | Euclid::eClearFlags_ZBuffer, Euclid::Color::Black, 1.0f, 0L);
_modules->getRenderEngine()->getRenderSystem()->beginScene();
//
renderGeometry();
//
_modules->getRenderEngine()->getRenderSystem()->endScene();
_modules->getRenderEngine()->getRenderSystem()->present(NULL, NULL, NULL);
//
return true;
}
bool WaitingForYou::postRender()
{
//
return true;
}
bool WaitingForYou::forePlay()
{
// call parent
Buddha::Game::forePlay();
// input handler
setInputMessageHandler(new InputMessageHandler);
// create modules
if (!createModules())
{
return false;
}
Record(Buddha::Logger::getInstancePtr()->getPath());
//
if (!setViewport())
{
return false;
}
//
// DragAcceptFiles(_hwnd, true);
//
if (!initGeometry())
{
return false;
}
//
if (!createFonts())
{
return false;
}
setProcess(Buddha::eProcess_CreateModules);
//
return true;
}
bool WaitingForYou::update(u32 current, u32 delta)
{
//
if (NULL == _modules)
{
return false;
}
if (!isActive())
{
return true;
}
if (_camera)
{
_camera->update();
}
// rotate
static Quaternion sQ;
static float sT;
//sT = current * 0.001f;
sQ.FromAngleAxis(sT, Vec3::UNIT_Y);
//
_modelMatrix.makeTransform(Vec3::ZERO, Vec3::UNIT_SCALE, sQ);
//
return true;
}
bool WaitingForYou::setViewport()
{
//
return true;
}
bool WaitingForYou::_initAxis()
{
return true;
}
bool WaitingForYou::initGeometry()
{
//
std::string heightFilePath = Buddha::FileSystem::getInstancePtr()->getDataDirectory() + "terrain\\height128.raw";
std::ifstream f(heightFilePath, std::ios::binary);
if (f.good())
{
int length = 0;
f.seekg(0, std::ios::end);
length = f.tellg();
_vertexNumber = length;
f.seekg(0, std::ios::beg);
u8* buffer = new u8[length];
f.read((char*)buffer, length);
//
{
_vb = _modules->getRenderEngine()->getBufferManager()->createVertexBuffer(length * sizeof(Euclid::sPositionTextureNormal), Euclid::eUsage_WriteOnly, Euclid::ePool_Default);
void* data = _vb->lock(0, 0, Euclid::eLock_Null);
Euclid::sPositionTextureNormal* dataPos = (Euclid::sPositionTextureNormal*)data;
int width = Euler::Basic::Sqrt(length);
_mapWidth = width;
int half_width = width / 2;
for (int i = 0; i != width; ++i)
for (int j = 0; j != width; ++j)
{
Euclid::sPositionTextureNormal p;
p.position.x = i - half_width;
p.position.z = j - half_width;
p.position.y = (buffer[j + i * width] - 128) * 0.25f;
p.texcoord.x = (float)j / (float)(width - 1);
p.texcoord.y = (float)i / (float)(width - 1);
p.normal = Vec3(0.0, 1.0, 0.0);
memcpy(dataPos, &p, sizeof(Euclid::sPositionTextureNormal));
++dataPos;
}
_vb->unLock();
//
{
_ib = _modules->getRenderEngine()->getBufferManager()->createIndexBuffer((width - 1) * (width - 1) * 2 * 3 * sizeof(u16), Euclid::eUsage_WriteOnly, Euclid::eFormat_Index16,Euclid::ePool_Default);
void* data = _ib->lock(0, 0, Euclid::eLock_Null);
u16* dataIndex = (u16*)data;
for (int i = 0; i != width - 1; ++i)
for (int j = 0; j != width - 1; ++j)
{
u16 baseIndex = j + i * width;
u16 indices[] = {
baseIndex, baseIndex + width, baseIndex + 1,
baseIndex + width, baseIndex + 1 + width, baseIndex + 1};
memcpy(dataIndex, indices, sizeof(u16) * 6);
dataIndex += 6;
}
_ib->unLock();
}
}
delete buffer;
buffer = NULL;
}
f.close();
//
//
_material = _modules->getRenderEngine()->getMaterialManager()->createMaterial(Euclid::eMaterialType_VertexTexture);
if (_material)
{
_material->setVertexDeclaration(Euclid::eVertexDeclarationType_PositionTextureNormal);
Euclid::MaterialVertexTexture* mvt = static_cast<Euclid::MaterialVertexTexture*>(_material);
mvt->setTexture("image/detailMap.tga");
}
//
_fx = _modules->getRenderEngine()->getEffectManager()->createEffectFromFile("shader\\PositionTextureLight.fx");
if (NULL == _fx)
{
return false;
}
//
_fx_axis = _modules->getRenderEngine()->getEffectManager()->createEffectFromFile("shader\\PositionColor.fx");
if (NULL == _fx_axis)
{
return false;
}
// axis
{
//
static float scale = 100;
//
_axis_vertices[0].position = Vec3::ZERO * scale;
_axis_vertices[0].color_ARGB = Euclid::Color::Red.getARGB();
_axis_vertices[1].position = Vec3::UNIT_X * scale;
_axis_vertices[1].color_ARGB = Euclid::Color::Red.getARGB();
//
_axis_vertices[2].position = Vec3::ZERO * scale;
_axis_vertices[2].color_ARGB = Euclid::Color::Green.getARGB();
_axis_vertices[3].position = Vec3::UNIT_Y * scale;
_axis_vertices[3].color_ARGB = Euclid::Color::Green.getARGB();
//
_axis_vertices[4].position = Vec3::ZERO * scale;
_axis_vertices[4].color_ARGB = Euclid::Color::Blue.getARGB();
_axis_vertices[5].position = Vec3::UNIT_Z * scale;
_axis_vertices[5].color_ARGB = Euclid::Color::Blue.getARGB();
}
//
_camera = new Euclid::Camera;
_camera->setPosition(Vec3(0.0f, 0.0f, 50.0f));
//
_cameraController = new Euclid::CameraControllerThirdPerson(_camera);
return true;
}
void WaitingForYou::renderGeometry()
{
//#define Show_FPS
#ifdef Show_FPS
std::ostringstream ss;
ss<<_fps;
if (_font)
{
_font->render(Vec3(100, 10, 0), Vec3(1, 0, 0), Euclid::Color::Red, ss.str());
}
#endif
// terrain
{
#define Show_Terrain
#ifdef Show_Terrain
_material->apply();
_modules->getRenderEngine()->getRenderSystem()->setStreamSource(0, _vb, 0, sizeof(Euclid::sPositionTextureNormal));
_modules->getRenderEngine()->getRenderSystem()->setIndices(_ib);
//
{
u32 passes = 0;
_fx->setMatrix("g_mWorld", _modelMatrix);
_fx->setMatrix("g_mWorldViewProjection", _camera->getProjectionMatrix() * _camera->getViewMatrix() * _cameraController->getMatrix() * _modelMatrix);
_fx->setTexture("g_MeshTexture", static_cast<Euclid::MaterialVertexTexture*>(_material)->_texture);
_fx->begin(&passes);
for (u32 i = 0; i != passes; ++i)
{
_fx->beginPass(i);
_modules->getRenderEngine()->getRenderSystem()->drawIndexedPrimitive(Euclid::ePrimitive_TriangleList, 0, 0, _mapWidth * _mapWidth, 0, (_mapWidth - 1) * (_mapWidth - 1) * 2);
_fx->endPass();
}
_fx->end();
}
#endif
}
// axis
{
#define Show_Axis
#ifdef Show_Axis
//
_modules->getRenderEngine()->getRenderSystem()->setVertexDeclaration(Euclid::eVertexDeclarationType_PositionColor);
//
{
u32 passes = 0;
_fx_axis->begin(&passes);
_fx_axis->setMatrix("g_mWorldViewProjection", _camera->getProjectionMatrix() * _camera->getViewMatrix() * _cameraController->getMatrix() * _modelMatrix);
for (u32 i = 0; i != passes; ++i)
{
_fx_axis->beginPass(i);
_modules->getRenderEngine()->getRenderSystem()->drawPrimitiveUP(Euclid::ePrimitive_LineList, 3, _axis_vertices, sizeof(Euclid::sPositionColor));
_fx_axis->endPass();
}
_fx_axis->end();
}
#endif
}
}
bool WaitingForYou::createFonts()
{
//
if(_modules->getRenderEngine()->getFontManager()->createFont(std::string("freetype\\simkai.ttf"), 18, Euclid::eFontProperty_Normal, "free"))
{
_font = _modules->getRenderEngine()->getFontManager()->getFont(std::string("free"));
}
//
return true;
}
void WaitingForYou::onDragAndDrop()
{
}
void WaitingForYou::onF1()
{
}
bool WaitingForYou::destroy()
{
Game::destroy();
if (_inputMessageHandler)
{
delete _inputMessageHandler;
_inputMessageHandler = NULL;
}
if (_material)
{
_material->destroy();
delete _material;
_material = 0;
}
if (_texture)
{
_texture->release();
_texture = NULL;
}
//
if (_camera)
{
delete _camera;
_camera = NULL;
}
//
if (_cameraController)
{
delete _cameraController;
_cameraController = NULL;
}
//
if (_fx)
{
_fx->destroy();
_fx = 0;
}
//
if (_fx_axis)
{
_fx_axis->destroy();
_fx_axis = 0;
}
//
if (_material)
{
delete _material;
_material = 0;
}
//
if (_vbInstances)
{
_vbInstances->destroy();
delete _vbInstances;
_vbInstances = NULL;
}
//
if (_ib)
{
_ib->destroy();
delete _ib;
_ib = NULL;
}
//
if (_vb)
{
_vb->destroy();
delete _vb;
_vb = NULL;
}
//
if (_modules)
{
_modules->destroy();
delete _modules;
_modules = NULL;
}
return true;
}
Euclid::CameraControllerThirdPerson* WaitingForYou::getCameraController()
{
return _cameraController;
}
void WaitingForYou::toggleFillMode()
{
static bool b = false;
if (b)
{
_modules->getRenderEngine()->getRenderSystem()->setRenderState(Euclid::eRenderState_FillMode, Euclid::eFillMode_WireFrame);
}
else
{
_modules->getRenderEngine()->getRenderSystem()->setRenderState(Euclid::eRenderState_FillMode, Euclid::eFillMode_Solid);
}
b = !b;
}
| [
"297191409@qq.com"
] | 297191409@qq.com |
027aca067d7f26bed79300a14b49b2dbbdcd7ace | ca64b4571ee17d5796833d60aa5f0d4368921d93 | /src/point.h | 16a7fc1fe899e473777a7a46ae48fabab53f9b23 | [
"BSD-3-Clause"
] | permissive | greatyang/kmeans | a92881a8e14017f0c3f67b698b2cac8c0c92c69d | 3af446c0cb973ae2f39a6e6a421ac396b3c243ac | refs/heads/master | 2022-11-25T23:04:17.220027 | 2016-06-21T07:19:34 | 2016-06-21T07:19:34 | 281,397,073 | 0 | 0 | BSD-3-Clause | 2020-07-21T12:52:00 | 2020-07-21T12:52:00 | null | UTF-8 | C++ | false | false | 1,060 | h | // Basic storage class for an n-dimensional point with a cluster assignment.
//
// Author: Felix Duvallet
#ifndef __KMEANS_POINT_H__
#define __KMEANS_POINT_H__
#include <vector>
#include <iostream>
class Point {
public:
Point() { }
// Initialize the number of dimensions, optionally set all values to zero.
Point(int num_dimensions, bool init_zeros = true);
Point(double x, double y, double z);
// Initialize from a vector.
Point(const std::vector<double> &vector);
~Point() { }
// Compute distance between two points.
static double distance(const Point &p1, const Point &p2);
// Adds a point to the current point.
void add(const Point &point);
// Update the cluster assignment. Returns true if cluster assignment
// changed, false if it stayed the same.
bool update(int k);
// Members: the data, the number of dimensions, and the cluster ID.
std::vector<double> data_;
int dimensions_;
int cluster_;
friend std::ostream &operator<<(std::ostream &target, const Point &point);
};
#endif // __KMEANS_POINT_H_
| [
"felix.duvallet@epfl.ch"
] | felix.duvallet@epfl.ch |
f8fc6f9d89bfcf0cc40f5f3daed4f2005154279c | a1fbf16243026331187b6df903ed4f69e5e8c110 | /cs/sdk/3d_sdk/maya/ver-2008/include/maya/MFnCompoundAttribute.h | 7d9d0e1055a80723469129a945bb6400b2c58c8a | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | OpenXRay/xray-15 | ca0031cf1893616e0c9795c670d5d9f57ca9beff | 1390dfb08ed20997d7e8c95147ea8e8cb71f5e86 | refs/heads/xd_dev | 2023-07-17T23:42:14.693841 | 2021-09-01T23:25:34 | 2021-09-01T23:25:34 | 23,224,089 | 64 | 23 | NOASSERTION | 2019-04-03T17:50:18 | 2014-08-22T12:09:41 | C++ | UTF-8 | C++ | false | false | 4,631 | h |
#ifndef _MFnCompoundAttribute
#define _MFnCompoundAttribute
//
//-
// ==========================================================================
// Copyright (C) 1995 - 2006 Autodesk, Inc., and/or its licensors. All
// rights reserved.
//
// The coded instructions, statements, computer programs, and/or related
// material (collectively the "Data") in these files contain unpublished
// information proprietary to Autodesk, Inc. ("Autodesk") and/or its
// licensors, which is protected by U.S. and Canadian federal copyright law
// and by international treaties.
//
// The Data may not be disclosed or distributed to third parties or be
// copied or duplicated, in whole or in part, without the prior written
// consent of Autodesk.
//
// The copyright notices in the Software and this entire statement,
// including the above license grant, this restriction and the following
// disclaimer, must be included in all copies of the Software, in whole
// or in part, and all derivative works of the Software, unless such copies
// or derivative works are solely in the form of machine-executable object
// code generated by a source language processor.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
// AUTODESK DOES NOT MAKE AND HEREBY DISCLAIMS ANY EXPRESS OR IMPLIED
// WARRANTIES INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF
// NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE,
// OR ARISING FROM A COURSE OF DEALING, USAGE, OR TRADE PRACTICE. IN NO
// EVENT WILL AUTODESK AND/OR ITS LICENSORS BE LIABLE FOR ANY LOST
// REVENUES, DATA, OR PROFITS, OR SPECIAL, DIRECT, INDIRECT, OR
// CONSEQUENTIAL DAMAGES, EVEN IF AUTODESK AND/OR ITS LICENSORS HAS
// BEEN ADVISED OF THE POSSIBILITY OR PROBABILITY OF SUCH DAMAGES.
// ==========================================================================
//+
//
// CLASS: MFnCompoundAttribute
//
// *****************************************************************************
//
// CLASS DESCRIPTION (MFnCompoundAttribute)
//
// MFnCompoundAttribute is the function set for compound dependency node
// attributes.
//
// Compound attributes allow the grouping of related attributes into a larger
// unit. It is possible to connect to a compound attribute as a whole, or
// to any of the individual children.
//
// For example, the three attributes RED, GREEN, and BLUE could be grouped
// into a compound attribute of type COLOR. It is then possible to connect
// two COLOR attributes together. This removes the need to connect each
// child explicitly.
//
// A second use for compound attributes is when there are multi attributes that
// relate to each other on an element-by-element basis. An example of this
// is the weighted matrix node that has a multi attribute with matrices that
// must be matched with the multi attribute that provides the weights for each
// matrix.
//
// *****************************************************************************
#if defined __cplusplus
// *****************************************************************************
// INCLUDED HEADER FILES
#include <maya/MFnAttribute.h>
// *****************************************************************************
// DECLARATIONS
class MString;
// *****************************************************************************
// CLASS DECLARATION (MFnCompoundAttribute)
/// Compound attribute function set. (OpenMaya) (OpenMaya.py)
/**
Function set for compound attributes of dependency nodes
*/
#ifdef _WIN32
#pragma warning(disable: 4522)
#endif // _WIN32
class OPENMAYA_EXPORT MFnCompoundAttribute : public MFnAttribute
{
declareMFn(MFnCompoundAttribute, MFnAttribute);
public:
///
MObject create( const MString& full,
const MString& brief,
MStatus* ReturnStatus = NULL );
///
MStatus addChild( const MObject & child );
///
MStatus removeChild( const MObject & child );
///
unsigned int numChildren( MStatus* ReturnStatus = NULL ) const;
///
MObject child( unsigned int index, MStatus* ReturnStatus = NULL ) const;
///
MStatus getAddAttrCmds(
MStringArray& cmds,
bool useLongNames = false
) const;
BEGIN_NO_SCRIPT_SUPPORT:
/// NO SCRIPT SUPPORT
declareMFnConstConstructor( MFnCompoundAttribute, MFnAttribute );
END_NO_SCRIPT_SUPPORT:
protected:
// No protected members
private:
// No private members
};
#ifdef _WIN32
#pragma warning(default: 4522)
#endif // _WIN32
// *****************************************************************************
#endif /* __cplusplus */
#endif /* _MFnCompoundAttribute */
| [
"paul-kv@yandex.ru"
] | paul-kv@yandex.ru |
288aeef64c3316c7889979dff440fa15abd5ef10 | 18e1d39f6d113ef29d4357b044ab28815e6d1ec1 | /worldMapScene.h | 9e44a28ed94c53472ec5e2598ed38d0a198d0ea7 | [] | no_license | GeunPark/_TeamProject | 524e367a2704b8f44785f13a5066ce81b88d3190 | e71bb551cd8af00951c41c368724761d90ca4c1d | refs/heads/master | 2021-09-20T17:09:53.444121 | 2018-08-12T21:46:40 | 2018-08-12T21:46:40 | 142,829,003 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 601 | h | #pragma once
#include "gameNode.h"
#include "foxPlayer.h"
struct tagWorld
{
image* img;
float x, y;
int count, index;
int alpha;
};
class worldMapScene : public gameNode
{
private:
tagWorld _backGround;
tagWorld _wayPoint;
tagWorld _wayRoad;
tagWorld _stagePoint;
tagWorld _stageTxt;
tagWorld _townTxt;
tagWorld _bossPoint;
tagWorld _bossRoad;
tagWorld _player;
bool move;
foxPlayer* _fox;
//테스트 임시 변수
int clearCount;
int loopCount;
public:
worldMapScene();
~worldMapScene();
HRESULT init(void);
void release(void);
void update(void);
void render(void);
};
| [
"junior2457@naver.com"
] | junior2457@naver.com |
459daffc4529a8ba1e154db9b5ce50aa3c429c8d | f1c01a3b5b35b59887bf326b0e2b317510deef83 | /SDK/SoT_BP_Ritual2_R_Pendant_classes.hpp | f5af711dd5903ec7ea3378c6155e3733edf70100 | [] | no_license | codahq/SoT-SDK | 0e4711e78a01f33144acf638202d63f573fa78eb | 0e6054dddb01a83c0c1f3ed3e6cdad5b34b9f094 | refs/heads/master | 2023-03-02T05:00:26.296260 | 2021-01-29T13:03:35 | 2021-01-29T13:03:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,101 | hpp | #pragma once
// Sea of Thieves (2.0) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_BP_Ritual2_R_Pendant_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_Ritual2_R_Pendant.BP_Ritual2_R_Pendant_C
// 0x0010 (0x0470 - 0x0460)
class ABP_Ritual2_R_Pendant_C : public AActor
{
public:
class UStaticMeshComponent* StaticMesh; // 0x0460(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* DefaultSceneRoot; // 0x0468(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_Ritual2_R_Pendant.BP_Ritual2_R_Pendant_C"));
return ptr;
}
void UserConstructionScript();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"igromanru@yahoo.de"
] | igromanru@yahoo.de |
7dfae029f61a9c2b35f2f7a90254971836b3df5d | b8295cebecedd98d52e87ea1acab870e9f14fcbb | /sources/OperationsExpert.cpp | 0ec67562ee038b802774f9a89bc8eb2c62fa2108 | [] | no_license | roei-birger/CPP_course_p4 | c02abe422a69b610845b1fe95c9a65334417b15d | b8a6ade8581edd530f0beafc0d5915d351a1c151 | refs/heads/master | 2023-04-27T12:11:05.644622 | 2021-05-11T13:12:05 | 2021-05-11T13:12:05 | 362,002,057 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 370 | cpp | #include "OperationsExpert.hpp"
using namespace std;
namespace pandemic
{
OperationsExpert::OperationsExpert(Board &b, City c) : Player(b, c) {}
string OperationsExpert::role()
{
return "OperationsExpert";
}
OperationsExpert &OperationsExpert::build()
{
currBoard.setResearchStation(currCity);
return *this;
}
}; | [
"roei1237@gmail.com"
] | roei1237@gmail.com |
90b39b98cc85846dc155533752e3cff4254e5d8d | 9e44370e60902484235bf474b64d5b2bdaf5c621 | /RPNCalculator/RPNCalculator/SubtractionOperation.h | 5572d940f490540ad823e56b1a4fe8600c4456fb | [] | no_license | guardhao104/COMP_3512_Lab5 | da3b18db998788ed03bbaab8d3c8cbae6d47bac4 | 730e5ef671b7b1444ed3458400b94cbf6864c515 | refs/heads/master | 2021-09-11T18:22:02.438198 | 2018-04-11T01:01:15 | 2018-04-11T01:01:15 | 121,799,555 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 315 | h | #pragma once
#include "AbstractOperation.h"
class SubtractionOperation : public AbstractOperation
{
public:
static const char OPERATION_CODE = '-';
SubtractionOperation() : AbstractOperation(OPERATION_CODE) {};
int perform(int a, int b) override { return a - b; };
virtual inline ~SubtractionOperation() {};
}; | [
"guardhao@outlook.com"
] | guardhao@outlook.com |
550dd9c79b7e5238869bbf71acd6b09e2ab8bcaf | 2b8b15793fa88c44163950a9543bcec36f168623 | /src/B3DetectorConstruction.cc | 84e03fa16038b86fc3f51c8cc660720ad24c8b37 | [] | no_license | gsmith23/Magnetic_Fields | b06a61d4531b086e0eea4b9f1d4078ddb61d20fa | 8c1f4b4710bde5322505ad63d35da4f406bd0ada | refs/heads/master | 2020-06-28T19:38:12.886711 | 2018-07-23T19:37:19 | 2018-07-23T19:37:19 | 74,477,288 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,256 | cc | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// $Id: B3DetectorConstruction.cc 71323 2013-06-13 16:54:23Z gcosmo $
//
/// \file B3DetectorConstruction.cc
/// \brief Implementation of the B3DetectorConstruction class
#include "B3DetectorConstruction.hh"
#include "G4NistManager.hh"
#include "G4Box.hh"
#include "G4Tubs.hh"
#include "G4LogicalVolume.hh"
#include "G4PVPlacement.hh"
#include "G4RotationMatrix.hh"
#include "G4Transform3D.hh"
#include "G4SDManager.hh"
#include "G4MultiFunctionalDetector.hh"
#include "G4VPrimitiveScorer.hh"
#include "G4PSEnergyDeposit.hh"
#include "G4PSDoseDeposit.hh"
#include "G4VisAttributes.hh"
#include "G4PhysicalConstants.hh"
#include "G4SystemOfUnits.hh"
#include "G4GlobalMagFieldMessenger.hh"
///// Task 1c.1
// Add here the include for the Magnetic Field Messenger
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
B3DetectorConstruction::B3DetectorConstruction()
: G4VUserDetectorConstruction(),
fCheckOverlaps(true)
{
// **Material definition**
DefineMaterials();
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
B3DetectorConstruction::~B3DetectorConstruction()
{ }
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void B3DetectorConstruction::DefineMaterials()
{
G4double a; // mass of a mole
G4double z; // mean number of protons
G4String name, symbol;
// Definition of element Oxygen
a=16.00*g/mole;
G4Element* elO = new G4Element(name="Oxygen", symbol="O", z=8., a);
a=28.09*g/mole;
G4Element* elSi = new G4Element(name="Silicon", symbol="Si", z=14., a);
a=174.97*g/mole;
G4Element* elLu = new G4Element(name="Lutetium", symbol="Lu", z=71., a);
a=88.91*g/mole;
G4Element* elYt = new G4Element(name="Yttrium", symbol="Lu", z=39., a);
G4double density;
density = 7.4*g/cm3;
// Declare the material with its density and number of components
G4Material * LSO;
LSO = new G4Material("Lu2SiO5",//name
density,//density
3);//number of elements
LSO->AddElement(elLu,2);
LSO->AddElement(elSi,1);
LSO->AddElement(elO,5);
density = 7.1*g/cm3;
G4Material * LYSO;
LYSO = new G4Material("LYSO",//name
density,//density
4);//number of elements
LYSO->AddElement(elLu,18);
LYSO->AddElement(elYt,2);
LYSO->AddElement(elSi,10);
LYSO->AddElement(elO,50);
// Dump the Table of registered materials
G4cout << *(G4Material::GetMaterialTable()) << G4endl;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
G4VPhysicalVolume* B3DetectorConstruction::Construct()
{
//
// First of all, fix the general parameters
//
// Gamma detector Parameters
//
// Crystals sizes
// Notice that the crystals will be rotated to be placed
// in the ring. What is called "cryst_dX" corresponds to
// to the z direction in the final system. The "cryst_dZ" is
// the "thickness" of the crystal in the ring
//
///// Task 1b.1:
// Modify the present geometry by slightly changing
// cryst_dY from 6. cm to 10. cm.
G4double cryst_dX = 10*cm, cryst_dY = 10*cm, cryst_dZ = 3*cm;
// Number of crystals per ring, and number of rings.
///// Task 1b.1:
// Change the crystals granularity in the detector,
// for example decrease the number of crystals per ring
// from 32 to 16
G4int nb_cryst = 16;
G4int nb_rings = 9;
// The inner radius of the ring is accomodated such that
// the nb_cryst crystals do not overlap. The approach presented
// here is pratically equivalent to ring_R1*twopi = nb_cryst*cryst_dY,
// i.e. the crystals fill entirely the inner circumference.
// The outer radius is calculated accordingly, by adding the thickness
// of the crystals and an extra term 1/cos. The computation might
// screw up if there are too-few crystals.
//
G4double dPhi = twopi/nb_cryst, half_dPhi = 0.5*dPhi;
G4double cosdPhi = std::cos(half_dPhi);
G4double tandPhi = std::tan(half_dPhi);
//
G4double ring_R1 = 0.5*cryst_dY/tandPhi;
G4double ring_R2 = (ring_R1+cryst_dZ)/cosdPhi;
//
// total length of the detector: nb_rings, each having
// thickness of cryst_dX along the z-axis (in the final reference
// frame).
G4double detector_dZ = nb_rings*cryst_dX;
//
G4NistManager* nist = G4NistManager::Instance();
// **Retrieve Nist Materials**
G4Material* default_mat = nist->FindOrBuildMaterial("G4_AIR");
//G4Material* cryst_mat = nist->FindOrBuildMaterial("Lu2SiO5");
G4Material* cryst_mat = nist->FindOrBuildMaterial("LYSO");
//G4Material* cryst_mat = nist->FindOrBuildMaterial("G4_SODIUM_IODIDE");
//
// ***** World *****
//
G4double world_sizeXY = 1.0*m;
G4double world_sizeZ = 1.0*m;
// Create the world volume as a box. This is big enough to contain
// all the detector rings.
G4Box* solidWorld =
new G4Box("World", //its name
0.5*world_sizeXY, 0.5*world_sizeXY, 0.5*world_sizeZ); //its size
// World Logical Volume definition
G4LogicalVolume* logicWorld =
new G4LogicalVolume(solidWorld, //its solid
default_mat, //its material
"World"); //its name
// World Physical Volume Placement at (0,0,0)
G4VPhysicalVolume* physWorld =
new G4PVPlacement(0, //no rotation
G4ThreeVector(), //at (0,0,0)
logicWorld, //its logical volume
"World", //its name
0, //its mother volume
false, //no boolean operation
0, //copy number
fCheckOverlaps); // checking overlaps
//
// ring
//
// define one ring as an "envelope" made of air. This will be filled
// by the crystals (dautgher volumes). The logical volume of the ring
// (which contains all daughters) will be then placed many times
//
G4Tubs* solidRing =
new G4Tubs("Ring", //name
ring_R1, //inner radius
ring_R2, //outer radius
0.5*cryst_dX, //height
0., //start angle
twopi); //spanning angle
G4LogicalVolume* logicRing =
new G4LogicalVolume(solidRing, //its solid
default_mat, //its material
"Ring"); //its name
//
// define crystal
//
// define one crystal now. It is made a bit smaller than the
// real size, to allow for wrapping. The same logical volume is
// placed many times in its mother volume, to produce the actual
// ring of crystals.
//
G4double gap = 0.5*mm; //a gap for wrapping
G4double dX = cryst_dX - gap, dY = cryst_dY - gap;
G4Box* solidCryst = new G4Box("crystal", dX/2, dY/2, cryst_dZ/2);
G4LogicalVolume* logicCryst =
new G4LogicalVolume(solidCryst, //its solid
cryst_mat, //its material
"CrystalLV"); //its name
// place crystals within a ring: loop
//
for (G4int icrys = 0; icrys < nb_cryst ; icrys++) {
G4double phi = icrys*dPhi;
// create a rotation matrix... (identity, by defauly)
G4RotationMatrix rotm = G4RotationMatrix();
//... and apply rotations. Notice that all rotations are
// referred to the mother volume.
rotm.rotateY(90*deg);
rotm.rotateZ(phi);
// Calculate position with respect to the reference frame
// of the mother volume
G4ThreeVector uz = G4ThreeVector(std::cos(phi), std::sin(phi),0.);
G4ThreeVector position = (ring_R1+0.5*cryst_dZ)*uz;
G4Transform3D transform = G4Transform3D(rotm,position);
// Place the crystal with the appropriate transformation
new G4PVPlacement(transform, //rotation,position
logicCryst, //its logical volume
"crystal", //its name
logicRing, //its mother volume
false, //no boolean operation
icrys, //copy number
fCheckOverlaps); // checking overlaps
}
//
// full detector. This is an "envelope" made of air which contains
// the rings. It is a big hollow cylinder, which will then host all rings
// as daughters (multiple placement). Notice that the cylinder is "hollow"
// so the central part will still belong to the mother (world) volume.
//
G4Tubs* solidDetector =
new G4Tubs("Detector", ring_R1, ring_R2, 0.5*detector_dZ, 0., twopi);
G4LogicalVolume* logicDetector =
new G4LogicalVolume(solidDetector, //its solid
default_mat, //its material
"Detector"); //its name
//
// place rings within detector
//
G4double OG = -0.5*(detector_dZ + cryst_dX);
for (G4int iring = 0; iring < nb_rings ; iring++) {
OG += cryst_dX;
new G4PVPlacement(0, //no rotation
G4ThreeVector(0,0,OG), //position
logicRing, //its logical volume
"ring", //its name
logicDetector, //its mother volume
false, //no boolean operation
iring, //copy number
fCheckOverlaps); // checking overlaps
}
//
// place detector in world, right in the centter
//
// new G4PVPlacement(0, //no rotation
// G4ThreeVector(), //at (0,0,0)
// logicDetector, //its logical volume
// "Detector", //its name
// logicWorld, //its mother volume
// false, //no boolean operation
// 0, //copy number
// fCheckOverlaps); // checking overlaps
//
// patient
//
// create a cylinder to simulate the brain of the patient. The
// G4_BRAIN_ICRP NIST material is used. The patient is placed at
// the center of the world.
G4double patient_radius = 8*cm;
G4double patient_dZ = 10*cm;
G4Material* patient_mat = nist->FindOrBuildMaterial("G4_BRAIN_ICRP");
G4Tubs* solidPatient =
new G4Tubs("Patient", 0., patient_radius, 0.5*patient_dZ, 0., twopi);
G4LogicalVolume* logicPatient =
new G4LogicalVolume(solidPatient, //its solid
patient_mat, //its material
"PatientLV"); //its name
//
// place patient in world
//
// new G4PVPlacement(0, //no rotation
// G4ThreeVector(), //at (0,0,0)
// logicPatient, //its logical volume
// "Patient", //its name
// logicWorld, //its mother volume
// false, //no boolean operation
// 0, //copy number
// fCheckOverlaps); // checking overlaps
///// Task 1b.2
// Here create the solid for patient's body
G4double body_dZ = 150*cm;
G4Tubs* solidBody = new G4Tubs("Body", // the name
0,
12*cm,
0.5*body_dZ,// in z direction
0., // in radians
twopi); // in radians
///// Task 1b.3
// Here recover the body-tissue material from NIST DB.
G4Material* body_mat = nist->FindOrBuildMaterial("G4_TISSUE_SOFT_ICRP");
// The create the body logical volume and set its visualization attributes
// following intructions on the exercise text
G4LogicalVolume* logicBody =
new G4LogicalVolume(solidBody, //its solid
body_mat, //its material
"BodyLV"); //its name
G4Colour red = G4Colour(1.0, 0.0, 0.0);
logicBody->SetVisAttributes(new G4VisAttributes(red));
///// Task 1b.4
// Here place an instance of the body-logical volume in the world volume
// new G4PVPlacement(0, //no rotation
// G4ThreeVector(0,0,-0.5*(body_dZ + patient_dZ + 0.002)),
// logicBody, //its logical volume
// "Body", //its name
// logicWorld, //its mother volume
// false, //no boolean operation
// 0, //copy number
// fCheckOverlaps); // checking overlaps
// Visualization attributes
// the two "envelopes" that were created to accomodate crystals and
// rings are set as invisible: they are made out of air and they are
// not real physical objects. They help to code the geometry in Geant4.
logicRing->SetVisAttributes (G4VisAttributes::Invisible);
logicDetector->SetVisAttributes (G4VisAttributes::Invisible);
// Print materials
G4cout << *(G4Material::GetMaterialTable()) << G4endl;
//always return the physical World
//
return physWorld;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void B3DetectorConstruction::ConstructSDandField()
{
//
// Register some of the volumes as "sensitive" and decide the
// type of sensitivity that they have
//
G4SDManager::GetSDMpointer()->SetVerboseLevel(1);
// declare crystal as a MultiFunctionalDetector scorer
//
// Create a new scorer (G4MultiFunctionalDetector) and set its
// "capability" to G4PSEnergyDeposit (will score total energy deposit)
G4MultiFunctionalDetector* cryst = new G4MultiFunctionalDetector("crystal");
G4VPrimitiveScorer* primitiv1 = new G4PSEnergyDeposit("edep");
cryst->RegisterPrimitive(primitiv1);
// Attach the scorer to the logical volume
SetSensitiveDetector("CrystalLV",cryst);
// declare patient as a MultiFunctionalDetector scorer
//
// Create a new scorer (G4MultiFunctionalDetector) and set its
// "capability" to G4PSDoseDeposit (will score total dose)
G4MultiFunctionalDetector* patient = new G4MultiFunctionalDetector("patient");
G4VPrimitiveScorer* primitiv2 = new G4PSDoseDeposit("dose");
patient->RegisterPrimitive(primitiv2);
// Attach the scorer to the proper logical volume
SetSensitiveDetector("PatientLV",patient);
///// Task 1c.1
// Here is the place to set the magnetic field
G4double Bz = 1 * tesla;
G4GlobalMagFieldMessenger* fMagFieldMessenger = new G4GlobalMagFieldMessenger(G4ThreeVector(0,0,Bz));
fMagFieldMessenger->SetVerboseLevel(1);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
| [
"gsmith23@ph.ed.ac.uk"
] | gsmith23@ph.ed.ac.uk |
53b59dd34064c10aebff80bc37d9a894be0a8abe | 23716a63aeffdddb0af68e8ed9acb22081e5f453 | /data/maps/AlteringCave_SubCave8/scripts.inc | 7a97b290afc94cfe0faa351a3270ad05f41b7464 | [] | no_license | Dabomstew/pokeemerald-ex-speedchoice | 7ed4ab716591140049ca567550a7c04d219e6e15 | dfe57e873e9a517efe43f45e5e7384fd08f3b12e | refs/heads/master | 2023-04-14T18:06:38.850868 | 2021-05-01T22:59:04 | 2021-05-01T22:59:04 | 363,359,727 | 1 | 0 | null | 2021-05-01T08:25:23 | 2021-05-01T08:25:23 | null | UTF-8 | C++ | false | false | 44 | inc | AlteringCave_SubCave8_MapScripts::
.byte 0
| [
"projectrevotpp@hotmail.com"
] | projectrevotpp@hotmail.com |
629638e8911603d13c54cf077141ef08f6014e0e | 6d1c143787686870c2bd792b75836c5a707dad3f | /Server/SceneServer/SSBattleMgr/SSBTreeCon_NoEnemyHero.h | a61e6001c06e4cd2a7b14c29630bd41a5f0eadc8 | [] | no_license | jakeowner/lastbattle | 66dad639dd0ac43fd46bac7a0005cc157d350cc9 | 22d310f5bca796461678ccf044389ed5f60e03e0 | refs/heads/master | 2021-05-06T18:25:48.932112 | 2017-11-24T08:21:59 | 2017-11-24T08:21:59 | 111,915,246 | 45 | 34 | null | 2017-11-24T12:19:15 | 2017-11-24T12:19:15 | null | UTF-8 | C++ | false | false | 602 | h | /*
* file name :SSBTreeCon_NoEnemyHero.h
* file mark :
* summary :
*
* version :1.0
* author :LiuLu
* complete date :November 11 2014
* summary :
*
*/
#pragma once
#include "stdafx.h"
#include "SSBTreeCondition.h"
namespace SceneServer{
class CSSHero;
class CSSBTreeCon_NoEnemyHero : public CSSBTreeCondition{
private:
public:
CSSBTreeCon_NoEnemyHero(INT32 id, INT32 parameters[]):CSSBTreeCondition(id,parameters){}
~CSSBTreeCon_NoEnemyHero(){};
BOOLEAN Travel(CSSAI_HeroRobot* pAI,CSSBTreeNode *&pActionNode,vector<SBTreeResult> *rstVec);
};
}; | [
"613961636@qq.com"
] | 613961636@qq.com |
f21ca3cc249d9e2f49829b236a08e14f41d06465 | 50fa39e33468fab2d9bbc807241c6e2297403f12 | /include/thor/meta/list/algorithm/replace.h | e63b714e909f8a727e90bb7e9cc4228483fe8aba | [] | no_license | wzppengpeng/thor | 41f63ed6eacdf59d712a8bdf40caeace8e4602fc | 169f2e2b2d81ab3af67f4f0e8f0f0bf4199baed9 | refs/heads/master | 2020-04-16T22:39:47.222022 | 2019-01-16T08:29:37 | 2019-01-16T08:29:37 | 165,978,049 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,626 | h | #ifndef THOR_META_LIST_ALGORITHM_REPLACE_H_
#define THOR_META_LIST_ALGORITHM_REPLACE_H_
#include "thor/meta/list/type_list.h"
/**
* replace the type A to be type B in TypeList
*/
TM_NS_BEGIN
// replace the first A to B
// ////////////////////////
template<typename TL, typename A, typename B> struct ListReplaceFirst;
template<typename Head, typename Tail, typename A, typename B>
struct ListReplaceFirst<TypeElem<Head, Tail>, A, B> {
using type = TypeElem<Head, typename ListReplaceFirst<Tail, A, B>::type>;
};
template<typename Head, typename Tail, typename B>
struct ListReplaceFirst<TypeElem<Head, Tail>, Head, B> {
using type = TypeElem<B, Tail>;
};
template<typename A, typename B>
struct ListReplaceFirst<NullType, A, B> {
using type = NullType;
};
// replace all A to B
// ////////////////////////
template<typename TL, typename A, typename B> struct ListReplaceAll;
template<typename Head, typename Tail, typename A, typename B>
struct ListReplaceAll<TypeElem<Head, Tail>, A, B> {
using type = TypeElem<Head, typename ListReplaceAll<Tail, A, B>::type>;
};
template<typename Head, typename Tail, typename B>
struct ListReplaceAll<TypeElem<Head, Tail>, Head, B> {
using type = TypeElem<B, typename ListReplaceAll<Tail, Head, B>::type>;
};
template<typename A, typename B>
struct ListReplaceAll<NullType, A, B> {
using type = NullType;
};
TM_NS_END
// help macro functions
#define __tl_replace__(...) typename TM_NS::ListReplaceFirst<__VA_ARGS__>::type
#define __tl_replace_all__(...) typename TM_NS::ListReplaceAll<__VA_ARGS__>::type
#endif /*THOR_META_LIST_ALGORITHM_REPLACE_H_*/ | [
"wzpycg@qq.com"
] | wzpycg@qq.com |
5f6f0560ea4b7263418363327c0644b019507e9c | c32ee8ade268240a8064e9b8efdbebfbaa46ddfa | /Libraries/m2sdk/mafia/gui/menu/C_ObjectCreator_TPL_335D96A2.h | 23ffb6347296613242052566ace01a7d03475423 | [] | no_license | hopk1nz/maf2mp | 6f65bd4f8114fdeb42f9407a4d158ad97f8d1789 | 814cab57dc713d9ff791dfb2a2abeb6af0e2f5a8 | refs/heads/master | 2021-03-12T23:56:24.336057 | 2015-08-22T13:53:10 | 2015-08-22T13:53:10 | 41,209,355 | 19 | 21 | null | 2015-08-31T05:28:13 | 2015-08-22T13:56:04 | C++ | UTF-8 | C++ | false | false | 547 | h | // auto-generated file (rttidump-exporter by h0pk1nz)
#pragma once
#include <mafia/gui/menu/C_Functor_TPL_8727B5BD.h>
namespace mafia
{
namespace gui
{
namespace menu
{
/** mafia::gui::menu::C_ObjectCreator<mafia::gui::menu::actions::C_SelectSaveDifficulty> (VTable=0x01E71E68) */
class C_ObjectCreator_TPL_335D96A2 : public C_Functor_TPL_8727B5BD
{
public:
virtual void vfn_0001_1A6E1F87() = 0;
virtual void vfn_0002_1A6E1F87() = 0;
virtual void vfn_0003_1A6E1F87() = 0;
};
} // namespace menu
} // namespace gui
} // namespace mafia
| [
"hopk1nz@gmail.com"
] | hopk1nz@gmail.com |
645a8b082dd40c4a063fea7187c52d38644f9095 | c475cd8531a94ffae69cc92371d41531dbbddb6c | /Libraries/breakpad/src/google_breakpad/processor/process_state.h | 728656f2bd7cffa0313a4fdd2242932209f5de4c | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown",
"BSD-3-Clause",
"LicenseRef-scancode-unicode-mappings"
] | permissive | WolfireGames/overgrowth | 72d3dd29cbd7254337265c29f8de3e5c32400114 | 594a2a4f9da0855304ee8cd5335d042f8e954ce1 | refs/heads/main | 2023-08-15T19:36:56.156578 | 2023-05-17T08:17:53 | 2023-05-17T08:20:36 | 467,448,492 | 2,264 | 245 | Apache-2.0 | 2023-05-09T07:29:58 | 2022-03-08T09:38:54 | C++ | UTF-8 | C++ | false | false | 8,042 | h | // Copyright (c) 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// process_state.h: A snapshot of a process, in a fully-digested state.
//
// Author: Mark Mentovai
#ifndef GOOGLE_BREAKPAD_PROCESSOR_PROCESS_STATE_H__
#define GOOGLE_BREAKPAD_PROCESSOR_PROCESS_STATE_H__
#include <string>
#include <vector>
#include "common/using_std_string.h"
#include "google_breakpad/common/breakpad_types.h"
#include "google_breakpad/processor/system_info.h"
#include "google_breakpad/processor/minidump.h"
namespace google_breakpad {
using std::vector;
class CallStack;
class CodeModules;
enum ExploitabilityRating {
EXPLOITABILITY_HIGH, // The crash likely represents
// a exploitable memory corruption
// vulnerability.
EXPLOITABILITY_MEDIUM, // The crash appears to corrupt
// memory in a way which may be
// exploitable in some situations.
EXPLOITABLITY_MEDIUM = EXPLOITABILITY_MEDIUM, // an old misspelling
EXPLOITABILITY_LOW, // The crash either does not corrupt
// memory directly or control over
// the affected data is limited. The
// issue may still be exploitable
// on certain platforms or situations.
EXPLOITABILITY_INTERESTING, // The crash does not appear to be
// directly exploitable. However it
// represents a condition which should
// be further analyzed.
EXPLOITABILITY_NONE, // The crash does not appear to represent
// an exploitable condition.
EXPLOITABILITY_NOT_ANALYZED, // The crash was not analyzed for
// exploitability because the engine
// was disabled.
EXPLOITABILITY_ERR_NOENGINE, // The supplied minidump's platform does
// not have a exploitability engine
// associated with it.
EXPLOITABILITY_ERR_PROCESSING // An error occured within the
// exploitability engine and no rating
// was calculated.
};
class ProcessState {
public:
ProcessState() : modules_(NULL) { Clear(); }
~ProcessState();
// Resets the ProcessState to its default values
void Clear();
// Accessors. See the data declarations below.
uint32_t time_date_stamp() const { return time_date_stamp_; }
uint32_t process_create_time() const { return process_create_time_; }
bool crashed() const { return crashed_; }
string crash_reason() const { return crash_reason_; }
uint64_t crash_address() const { return crash_address_; }
string assertion() const { return assertion_; }
int requesting_thread() const { return requesting_thread_; }
const vector<CallStack*>* threads() const { return &threads_; }
const vector<MemoryRegion*>* thread_memory_regions() const {
return &thread_memory_regions_;
}
const SystemInfo* system_info() const { return &system_info_; }
const CodeModules* modules() const { return modules_; }
const vector<const CodeModule*>* modules_without_symbols() const {
return &modules_without_symbols_;
}
const vector<const CodeModule*>* modules_with_corrupt_symbols() const {
return &modules_with_corrupt_symbols_;
}
ExploitabilityRating exploitability() const { return exploitability_; }
private:
// MinidumpProcessor and MicrodumpProcessor are responsible for building
// ProcessState objects.
friend class MinidumpProcessor;
friend class MicrodumpProcessor;
// The time-date stamp of the minidump (time_t format)
uint32_t time_date_stamp_;
// The time-date stamp when the process was created (time_t format)
uint32_t process_create_time_;
// True if the process crashed, false if the dump was produced outside
// of an exception handler.
bool crashed_;
// If the process crashed, the type of crash. OS- and possibly CPU-
// specific. For example, "EXCEPTION_ACCESS_VIOLATION" (Windows),
// "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS" (Mac OS X), "SIGSEGV"
// (other Unix).
string crash_reason_;
// If the process crashed, and if crash_reason implicates memory,
// the memory address that caused the crash. For data access errors,
// this will be the data address that caused the fault. For code errors,
// this will be the address of the instruction that caused the fault.
uint64_t crash_address_;
// If there was an assertion that was hit, a textual representation
// of that assertion, possibly including the file and line at which
// it occurred.
string assertion_;
// The index of the thread that requested a dump be written in the
// threads vector. If a dump was produced as a result of a crash, this
// will point to the thread that crashed. If the dump was produced as
// by user code without crashing, and the dump contains extended Breakpad
// information, this will point to the thread that requested the dump.
// If the dump was not produced as a result of an exception and no
// extended Breakpad information is present, this field will be set to -1,
// indicating that the dump thread is not available.
int requesting_thread_;
// Stacks for each thread (except possibly the exception handler
// thread) at the time of the crash.
vector<CallStack*> threads_;
vector<MemoryRegion*> thread_memory_regions_;
// OS and CPU information.
SystemInfo system_info_;
// The modules that were loaded into the process represented by the
// ProcessState.
const CodeModules *modules_;
// The modules that didn't have symbols when the report was processed.
vector<const CodeModule*> modules_without_symbols_;
// The modules that had corrupt symbols when the report was processed.
vector<const CodeModule*> modules_with_corrupt_symbols_;
// The exploitability rating as determined by the exploitability
// engine. When the exploitability engine is not enabled this
// defaults to EXPLOITABILITY_NOT_ANALYZED.
ExploitabilityRating exploitability_;
};
} // namespace google_breakpad
#endif // GOOGLE_BREAKPAD_PROCESSOR_PROCESS_STATE_H__
| [
"max@autious.net"
] | max@autious.net |
d6d9f5e382316214e129a83a9b24a4f2fa072173 | 3a7434fcdce3d90a2518ec62f37f027e7a207585 | /27. regex/main.cpp | 5e74da911e5c01c3613001ed6b1b2b91ced86fea | [] | no_license | shoter/ADV_Seminarium | 6d792dc40ecd2df85acecc842aaa31d0e0cd5539 | 7237aadf99a41dfaf6e6ac524ec501b794e516e6 | refs/heads/master | 2021-01-10T03:17:22.989661 | 2016-04-06T00:13:33 | 2016-04-06T00:13:33 | 55,480,293 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,660 | cpp | #include <iostream>
#include <dirent.h>
#include <vector>
#include <regex>
#include <string>
#include <algorithm>
std::vector<std::string> getDirectories(const char * location)
{
DIR *dir;
std::vector<std::string> vec;
struct dirent *ent;
if ((dir = opendir (location)) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
vec.push_back(ent->d_name);
}
closedir (dir);
}
return vec;
}
using namespace std::regex_constants;
int main()
{
auto directories = getDirectories("c:\\");
std::regex dirExpr( "^[aeiouy].*", icase );
for(auto directory : directories)
{
if(std::regex_match(directory, dirExpr))
{
std::cout << directory << std::endl;
}
}
std::cout << "\nUsuniemy teraz wszystkie samogloski" << std::endl;
std::cin.get();
std::regex replaceExpr( "[aeiouy]", icase);
for(auto directory : directories)
{
std::string str;
str = std::regex_replace(directory, replaceExpr, ".", format_no_copy);
std::cout << str << std::endl;
}
std::cout << "\n\nCzas na regex_search" << std::endl;
std::cin.get();
std::regex searchExpr("^(.+)\\.(.+)$", icase);
std::smatch matchResults;
for(auto directory : directories)
{
std::regex_search(directory, matchResults, searchExpr);
if(std::regex_match(directory, searchExpr))
{
std::cout << "Plik " << matchResults[1] << " ma rozszerzenie " << matchResults[2] << std::endl;
}
}
std::cin.get();
return 0;
}
| [
"lubiebardzozelki@gmail.com"
] | lubiebardzozelki@gmail.com |
d962ab189552266680b8211b9c5802150935b1c8 | 3837a03fceb06dbe8d4546366750cf5c5478819d | /include/dlstreamer/opencl/tensor_ref_counted.h | 0b6f7fd0b58116c73cf542b14c3d52f64323067d | [
"MIT"
] | permissive | dlstreamer/dlstreamer | b1453b1a79437cf74eaf0438e38f809dd82afae2 | 20f2bb6a0be2cfdb351ab2297a4ac7c4db090ed8 | refs/heads/master | 2023-08-18T14:54:36.496564 | 2023-03-03T20:31:16 | 2023-03-03T20:51:34 | 175,417,729 | 135 | 53 | MIT | 2023-02-07T14:59:51 | 2019-03-13T12:35:56 | C++ | UTF-8 | C++ | false | false | 1,241 | h | /*******************************************************************************
* Copyright (C) 2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
******************************************************************************/
#pragma once
#include "dlstreamer/opencl/tensor.h"
namespace dlstreamer {
class OpenCLTensorRefCounted : public OpenCLTensor {
public:
OpenCLTensorRefCounted(const TensorInfo &info, ContextPtr context, cl_mem mem) : OpenCLTensor(info, context, mem) {
clRetainMemObject(mem);
}
OpenCLTensorRefCounted(const TensorInfo &info, ContextPtr context)
: OpenCLTensor(info, context, create_buffer(info, context)) {
}
~OpenCLTensorRefCounted() {
clReleaseMemObject(clmem());
}
private:
cl_mem create_buffer(const TensorInfo &info, ContextPtr context) {
cl_context clcontext = static_cast<cl_context>(context->handle(OpenCLContext::key::cl_context));
cl_int errcode = 0;
cl_mem clmem = clCreateBuffer(clcontext, 0, info.nbytes(), 0, &errcode);
if (!clmem || errcode)
throw std::runtime_error("Error creating OpenCL buffer " + std::to_string(errcode));
return clmem;
}
};
} // namespace dlstreamer
| [
"mikhail.y.nikolsky@intel.com"
] | mikhail.y.nikolsky@intel.com |
ddc878f2b673205bcb35a1700fb5fa15b057f9d6 | 19a98c9965cf0ece2b1c419852f7c7b02b6aca52 | /Task5/Task5/Task5.cpp | fdd8fd2acd6eb9a8bc3287f19079614242b4729b | [] | no_license | rekinx/SW | 273a3429e9d7bc709fe5b503c2a981150e596ce2 | 03dc36a248f5b653fdf3ce6565aa2a90ee38aaf5 | refs/heads/main | 2023-08-28T06:37:36.842928 | 2021-10-27T22:56:09 | 2021-10-27T22:56:09 | 411,675,504 | 0 | 0 | null | 2021-09-29T13:00:00 | 2021-09-29T12:59:59 | null | UTF-8 | C++ | false | false | 917 | cpp | #include<string>
#include<iostream>
#include <random>
using namespace std;
int main() {
int num1 = rand() % 10, num2 = rand() % 10, num3 = rand() % 10, num4 = rand() % 10, num; //5 задание
string hid_num, ans = "0000";
hid_num = to_string(num1) + to_string(num2) + to_string(num3) + to_string(num4);
for (int i = 0; i <= 9; i++) {
ans.replace(3, 1, to_string(i));
if (ans == hid_num) {
cout << "password: " << ans << endl;
}
for (int j = 0; j <= 9; j++) {
ans.replace(2, 1, to_string(j));
if (ans == hid_num) {
cout << "password: " << ans << endl;
}
for (int l = 0; l <= 9; l++) {
ans.replace(1, 1, to_string(l));
if (ans == hid_num) {
cout << "password: " << ans << endl;
}
for (int f = 0; f <= 9; f++) {
ans.replace(0, 1, to_string(f));
if (ans == hid_num) {
cout << "password: " << ans << endl;
}
}
}
}
}
system("pause");
return 0;
} | [
"makary787898@gmail.com"
] | makary787898@gmail.com |
179bbd34aac622ea9303d908eee753fe0a849536 | 85e5e67b0ddb32701b6aad5c3d2a428c768bb41c | /Engine/Camera.h | b3782ce30e520ae09f62cb6f1bc7d86c3c8b1416 | [] | no_license | lim-james/Allure | a6ebca6b2ca1c70bc2108f8ae710c2a88117657d | 6d837a49254d181babf546d829fc871e468d66db | refs/heads/master | 2021-07-18T04:31:08.130059 | 2020-08-21T03:30:54 | 2020-08-21T03:30:54 | 205,639,206 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,587 | h | #ifndef CAMERA_H
#define CAMERA_H
#include "Component.h"
#include "Framebuffer.h"
#include <Events/Event.h>
#include <Math/Vectors.h>
#include <Math/Mat4.hpp>
#include <Bit/BitField.h>
#define PERSPECTIVE 0
#define ORTHOGRAPHIC 1
struct Camera : Component {
using base_type = Camera;
bool isHidden;
bool shouldClear;
vec4f clearColor;
short projection;
float FOV;
float nearPlane;
float farPlane;
bool captureDepth;
BitField cullingMask;
Camera();
~Camera() override;
void Initialize() override;
Component* Clone() const override;
void SetActive(bool const& state) override;
float const& GetSize() const;
void SetSize(float const& value);
void SetMatch(float const& value);
float const& GetDepth() const;
void SetDepth(float const& value);
mat4f GetProjectionMatrix() const;
vec2f const& GetFrameSize() const;
void SetViewportRect(vec4f const& rect);
vec4f const& GetViewport() const;
void SetFramebuffer(Framebuffer* const fb);
Framebuffer* const GetFramebuffer() const;
void SetDepthBuffer(Framebuffer* const fb);
Framebuffer* const GetDepthBuffer() const;
vec2f ScreenToWorldPosition(vec2f const& mousePosition) const;
bool UseProcess() const;
void SetUseProcess(bool const& state);
private:
float size;
float match;
float depth;
vec4f viewportRect;
float aspectRatio;
float left, right, bottom, top;
vec2f frameSize;
vec4f viewport;
vec2f windowSize;
Framebuffer* framebuffer;
Framebuffer* depthBuffer;
bool useProcess;
void WindowResizeHandler(Events::Event* event);
void UpdateViewport();
};
#endif | [
"jameslimbj@gmail.com"
] | jameslimbj@gmail.com |
e0796085a97e81398e531732f92cad449724750b | 92a4bff0837ee0189cdd5379bb1b1085611a23b9 | /indexing/analyzer/StemmerLib/stemming.h | 7ad80ab04e68a99f6b4b5f6e18c674e8933ca8ff | [] | no_license | actnet/saedb | 6c17ab192b7c939efad5aef4f27b80a053b7c10e | b195293bd10e82a294381cb1553f8d55d9779ec7 | refs/heads/master | 2021-01-20T08:47:32.496312 | 2015-02-13T07:56:42 | 2015-02-13T07:56:42 | 24,217,636 | 7 | 1 | null | 2014-10-09T06:41:35 | 2014-09-19T05:38:21 | C++ | UTF-8 | C++ | false | false | 99,343 | h | /***************************************************************************
stemming.h - description
-------------------
begin : Sat Apr 26 2003
copyright : (C) 2003 by Blake Madden
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the BSD License. *
* *
***************************************************************************/
#ifndef __STEM_H__
#define __STEM_H__
#include <algorithm>
#include "utilities.h"
#include "string_util.h"
#include "common_lang_constants.h"
#include "punctuation.h"
using namespace common_lang_constants;
namespace stemming
{
enum stemming_type
{
no_stemming,
danish,
dutch,
english,
finnish,
french,
german,
italian,
norwegian,
portuguese,
spanish,
swedish,
STEMMING_TYPE_COUNT
};
//these characters should not appear in an indexed word
const wchar_t UPPER_Y_HASH = 7;//bell
const wchar_t LOWER_Y_HASH = 9;//tab
const wchar_t UPPER_I_HASH = 10;//line feed
const wchar_t LOWER_I_HASH = 11;//vertical tab
const wchar_t UPPER_U_HASH = 12;//form feed (new page)
const wchar_t LOWER_U_HASH = 13;//carriage return
//language constants
static const wchar_t FRENCH_VOWELS[] = { 97, 101, 105, 111, 117, 121, 0xE2,
0xE0, 0xEB, 0xE9,
0xEA, 0xE8, 0xEF,
0xEE, 0xF4, 0xFB,
0xF9, 65, 69, 73, 79, 85, 89, 0xC2,
0xC0, 0xCB, 0xC9,
0xCA, 0xC8, 0xCF,
0xCE, 0xD4, 0xDB,
0xD9, 0 };
static const wchar_t FRENCH_ACCENTED_E[] = { 0xE9, 0xE8,
0xC9, 0xC8, 0 };
static const wchar_t FRENCH_AIOUES[] = { 97, 105, 111, 117, 0xE8, 115, 65, 73, 79, 85,
0xC8, 83, 0 };
static const wchar_t GERMAN_VOWELS[] = { 97, 101, 105, 111, 117, 0xFC, 121,
0xE4, 0xF6, 65, 0xC4,
69, 73, 79, 0xD6, 85, 0xDC, 89, 0 };
static const wchar_t DANISH_VOWELS[] = { 97, 101, 105, 111, 117, 121, 0xE6,
0xE5, 0xF8, 65, 69, 73, 79, 85, 89,
0xC6, 0xC5, 0xD8, 0 };
static const wchar_t DANISH_ALPHABET[] = { 97, 98, 99, 100, 102, 103, 104, 106, 107, 108, 109, 110, 111, 112, 114,
116, 118, 121, 122, 0xE5, 65, 66, 67, 68, 70, 71, 72, 74, 75, 76, 77, 78, 79,
80, 82, 84, 86, 89, 90, 0xC5, 0 };
static const wchar_t FINNISH_VOWELS[] = { 97, 101, 105, 111, 117, 121, 0xE4, 0xF6, 65, 69, 73, 79, 85, 89,
0xC4, 0xD6, 0 };
static const wchar_t FINNISH_VOWELS_NO_Y[] = { 97, 101, 105, 111, 117, 0xE4, 0xF6, 65, 69, 73, 79, 85,
0xC4, 0xD6, 0 };
static const wchar_t FINNISH_VOWELS_SIMPLE[] = { 97, 101, 105, 0xE4, 65, 69, 73, 0xC4, 0 };
static const wchar_t FINNISH_STEP_1_SUFFIX[] = { 110, 116, 97, 101, 105, 111, 117, 121, 0xE4,
0xF6, 78, 84, 65, 69, 73, 79, 85, 89, 0xC4, 0xD6, 0 };
static const wchar_t DUTCH_VOWELS[] = { 97, 101, 105, 111, 117, 121, 0xE8,
65, 69, 73, 79, 85, 89, 0xC8, 0 };
static const wchar_t DUTCH_KDT[] = { 107, 100, 116, 75, 68, 84, 0 };
static const wchar_t DUTCH_S_ENDING[] = { 97, 101, 0xE8, 105, 111, 117, 121, 106, 65, 69,
0xC8, 73, 79, 85, 89, 74, 0 };
static const wchar_t NORWEGIAN_VOWELS[] = { 97, 101, 105, 111, 0xF8, 117, 121, 0xE5,
0xE6, 0xC5, 65, 0xC6, 69, 73, 79,
0xD8, 85, 89, 0 };
static const wchar_t PORTUGUESE_VOWELS[] = { 97, 101, 105, 111, 117, 0xE1, 0xE9,
0xED, 0xF3, 0xFA, 0xE2,
0xEA, 0xF4, 65, 69, 73, 79, 85, 0xC1,
0xC9, 0xCD, 0xD3, 0xDA,
0xC2, 0xCA, 0xD4, 0 };
static const wchar_t SPANISH_VOWELS[] = { 97, 101, 105, 111, 117, 0xE1, 0xE9,
0xED, 0xF3, 0xFA, 0xFC,
65, 69, 73, 79, 85, 0xC1, 0xC9, 0xCD,
0xD3, 0xDA, 0xDC, 0 };
static const wchar_t SWEDISH_VOWELS[] = { 97, 101, 105, 111, 117, 121, 0xE5,
0xE4, 0xF6, 65, 69, 73, 79, 85, 89,
0xC5, 0xC4, 0xD6, 0 };
static const wchar_t ITALIAN_VOWELS[] = { 97, 101, 105, 111, 117, 0xE0,
0xE8, 0xEC, 0xF2,
0xF9, 65, 69, 73, 79, 85, 0xC0,
0xC8, 0xCC, 0xD2,
0xD9, 0 };
static const wchar_t ITALIAN_VOWELS_SIMPLE[] = { 97, 101, 105, 111, 0xE0,
0xE8, 0xEC, 0xF2,
65, 69, 73, 79, 0xC0, 0xC8,
0xCC, 0xD2, 0 };
/**The template argument for the stemmers are the type of std::basic_string that you are trying to stem,
by default std::wstring (Unicode strings). As long as the char type of your basic_string is wchar_t,
then you can use any type of basic_string. This is to say, if your basic_string has a custom
char_traits or allocator, then just specify it in your template argument to the stemmer.
\example
typedef std::basic_string<wchar_t, myTraits, myAllocator> myString;<br>
myString word(L"documentation");<br>
stemming::english_stem<myString> StemEnglish;<br>
StemEnglish(word);*/
template <typename string_typeT = std::wstring>
class stem
{
public:
stem() : m_r1(0), m_r2(0), m_rv(0) {}
protected:
//R1, R2, RV functions
void find_r1(const string_typeT& text,
const wchar_t* vowel_list)
{
//see where the R1 section begin
//R1 is the region after the first consonant after the first vowel
size_t start = text.find_first_of(vowel_list, 0);
if (start == string_typeT::npos)
{
//we need at least need a vowel somewhere in the word
m_r1 = text.length();
return;
}
m_r1 = text.find_first_not_of(vowel_list,++start);
if (get_r1() == string_typeT::npos)
{
m_r1 = text.length();
}
else
{
++m_r1;
}
}
void find_r2(const string_typeT& text,
const wchar_t* vowel_list)
{
size_t start = 0;
//look for R2--not required for all criteria.
//R2 is the region after the first consonant after the first vowel after R1
if (get_r1() != text.length() )
{
start = text.find_first_of(vowel_list, get_r1());
}
else
{
start = string_typeT::npos;
}
if (start != string_typeT::npos &&
static_cast<int>(start) != static_cast<int>(text.length())-1)
{
m_r2 = text.find_first_not_of(vowel_list,++start);
if (get_r2() == string_typeT::npos)
{
m_r2 = text.length();
}
else
{
++m_r2;
}
}
else
{
m_r2 = text.length();
}
}
void find_spanish_rv(const string_typeT& text,
const wchar_t* vowel_list)
{
//see where the RV section begin
if (text.length() < 4)
{
m_rv = text.length();
return;
}
//if second letter is a consonant
if (!string_util::is_one_of(text[1], vowel_list) )
{
size_t start = text.find_first_of(vowel_list, 2);
if (start == string_typeT::npos)
{
//can't find next vowel
m_rv = text.length();
return;
}
else
{
m_rv = start+1;
}
}
//if first two letters are vowels
else if (string_util::is_one_of(text[0], vowel_list) &&
string_util::is_one_of(text[1], vowel_list))
{
size_t start = text.find_first_not_of(vowel_list, 2);
if (start == string_typeT::npos)
{
//can't find next consonant
m_rv = text.length();
return;
}
else
{
m_rv = start+1;
}
}
//consonant/vowel at beginning
else if (!string_util::is_one_of(text[0], vowel_list) &&
string_util::is_one_of(text[1], vowel_list))
{
m_rv = 3;
}
else
{
m_rv = text.length();
}
}
/*If the word begins with two vowels, RV is the region after the third letter,
otherwise the region after the first vowel not at the beginning of the word,
or the end of the word if these positions cannot be found.
(Exceptionally, par, col or tap, at the begining of a word is also taken to be the region before RV.)*/
void find_french_rv(const string_typeT& text,
const wchar_t* vowel_list)
{
//see where the RV section begin
if (text.length() < 3)
{
m_rv = text.length();
return;
}
/*Exceptions: If the word begins with these then RV goes right after them,
whether it be a letter or simply the end of the word.*/
if ((text.length() >= 3) && (
(is_either<wchar_t>(text[0], LOWER_P, UPPER_P) &&
is_either<wchar_t>(text[1], LOWER_A, UPPER_A) &&
is_either<wchar_t>(text[2], LOWER_R, UPPER_R) ) || //par
(is_either<wchar_t>(text[0], LOWER_C, UPPER_C) &&
is_either<wchar_t>(text[1], LOWER_O, UPPER_O) &&
is_either<wchar_t>(text[2], LOWER_L, UPPER_L) ) || //col
(is_either<wchar_t>(text[0], LOWER_T, UPPER_T) &&
is_either<wchar_t>(text[1], LOWER_A, UPPER_A) &&
is_either<wchar_t>(text[2], LOWER_P, UPPER_P) )//tap
))
{
m_rv = 3;
return;
}
//if first two letters are vowels
if (string_util::is_one_of(text[0], vowel_list) &&
string_util::is_one_of(text[1], vowel_list))
{
m_rv = 3;
}
else
{
size_t start = text.find_first_not_of(vowel_list, 0);
if (start == string_typeT::npos)
{
//can't find first consonant
m_rv = text.length();
return;
}
start = text.find_first_of(vowel_list, start);
if (start == string_typeT::npos)
{
//can't find first vowel
m_rv = text.length();
return;
}
m_rv = start+1;
}
}
void find_russian_rv(const string_typeT& text,
const wchar_t* vowel_list)
{
size_t start = text.find_first_of(vowel_list);
if (start == string_typeT::npos)
{
//can't find first vowel
m_rv = text.length();
return;
}
else
{
m_rv = start+1;
}
}
inline void update_r_sections(const string_typeT& text)
{
if (get_r1() > text.length() )
{
m_r1 = text.length();
}
if (get_r2() > text.length() )
{
m_r2 = text.length();
}
if (get_rv() > text.length() )
{
m_rv = text.length();
}
}
//---------------------------------------------
void trim_western_punctuation(string_typeT& text)
{
if (text.length() >= 3 &&
punctuation::is_western_character::is_apostrophe(text[text.length()-3]) &&
is_either<wchar_t>(text[text.length()-2], LOWER_S, UPPER_S) &&
punctuation::is_western_character::is_apostrophe(text[text.length()-1]) )
{
text.erase(text.length()-3);
}
else if (text.length() >= 2 &&
punctuation::is_western_character::is_apostrophe(text[text.length()-2]) &&
is_either<wchar_t>(text[text.length()-1], LOWER_S, UPPER_S) )
{
text.erase(text.length()-2);
}
else if (punctuation::is_western_character::is_apostrophe(text[text.length()-1]))
{
text.erase(text.length()-1);
}
while (text.length() )
{
const wchar_t lastChar = text[text.length()-1];
if (!(lastChar >= 48 && lastChar <= 57) &&
!(lastChar >= 65 && lastChar <= 90) &&
!(lastChar >= 97 && lastChar <= 122) &&
!(lastChar >= 192 && lastChar <= 246) &&
!(lastChar >= 248 && lastChar <= 255) &&
lastChar != 0xA0)//space
{
text.erase(text.length()-1);
}
else
{
break;
}
}
while (text.length() )
{
if (!(text[0] >= 48 && text[0] <= 57) &&
!(text[0] >= 65 && text[0] <= 90) &&
!(text[0] >= 97 && text[0] <= 122) &&
!(text[0] >= 192 && text[0] <= 246) &&
!(text[0] >= 248 && text[0] <= 255) )
{
text.erase(0, 1);
}
else
{
break;
}
}
}
//suffix removal determinant functions
///is_suffix for one character
inline bool is_suffix(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U) const
{
if (text.length() < 1)
{ return false; }
return is_either<wchar_t>(text[text.length()-1], suffix1L, suffix1U);
}
///is_suffix for two characters
inline bool is_suffix(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U) const
{
if (text.length() < 2)
{
return false;
}
return is_either<wchar_t>(text[text.length()-2], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-1], suffix2L, suffix2U);
}
///is_suffix for three characters
inline bool is_suffix(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U) const
{
if (text.length() < 3)
{
return false;
}
return is_either<wchar_t>(text[text.length()-3], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-2], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-1], suffix3L, suffix3U);
}
///is_suffix for four characters
inline bool is_suffix(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U) const
{
if (text.length() < 4)
{
return false;
}
return is_either<wchar_t>(text[text.length()-4], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-3], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-2], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-1], suffix4L, suffix4U);
}
///is_suffix for five characters
inline bool is_suffix(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U) const
{
if (text.length() < 5)
{
return false;
}
return is_either<wchar_t>(text[text.length()-5], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-4], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-3], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-2], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-1], suffix5L, suffix5U);
}
///is_suffix for six characters
inline bool is_suffix(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U) const
{
if (text.length() < 6)
{
return false;
}
return is_either<wchar_t>(text[text.length()-6], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-5], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-4], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-3], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-2], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-1], suffix6L, suffix6U);
}
///is_suffix for seven characters
inline bool is_suffix(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U,
const wchar_t suffix7L, const wchar_t suffix7U) const
{
if (text.length() < 7)
{
return false;
}
return is_either<wchar_t>(text[text.length()-7], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-6], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-5], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-4], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-3], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-2], suffix6L, suffix6U) &&
is_either<wchar_t>(text[text.length()-1], suffix7L, suffix7U);
}
///is_suffix for eight characters
inline bool is_suffix(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U,
const wchar_t suffix7L, const wchar_t suffix7U,
const wchar_t suffix8L, const wchar_t suffix8U) const
{
if (text.length() < 8)
{
return false;
}
return is_either<wchar_t>(text[text.length()-8], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-7], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-6], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-5], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-4], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-3], suffix6L, suffix6U) &&
is_either<wchar_t>(text[text.length()-2], suffix7L, suffix7U) &&
is_either<wchar_t>(text[text.length()-1], suffix8L, suffix8U);
}
///is_suffix for nine characterss
inline bool is_suffix(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U,
const wchar_t suffix7L, const wchar_t suffix7U,
const wchar_t suffix8L, const wchar_t suffix8U,
const wchar_t suffix9L, const wchar_t suffix9U) const
{
if (text.length() < 9)
{
return false;
}
return is_either<wchar_t>(text[text.length()-9], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-8], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-7], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-6], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-5], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-4], suffix6L, suffix6U) &&
is_either<wchar_t>(text[text.length()-3], suffix7L, suffix7U) &&
is_either<wchar_t>(text[text.length()-2], suffix8L, suffix8U) &&
is_either<wchar_t>(text[text.length()-1], suffix9L, suffix9U);
}
///comparison for two characters
inline bool is_partial_suffix(const string_typeT& text,
const size_t start_index,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U)
{
if ((start_index+2) >= text.length())
{ return false; }
return (is_either<wchar_t>(text[start_index], suffix1L, suffix1U) &&
is_either<wchar_t>(text[start_index+1], suffix2L, suffix2U));
}
///comparison for three characters
inline bool is_partial_suffix(const string_typeT& text,
const size_t start_index,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U)
{
if ((start_index+3) >= text.length())
{ return false; }
return (is_either<wchar_t>(text[start_index], suffix1L, suffix1U) &&
is_either<wchar_t>(text[start_index+1], suffix2L, suffix2U) &&
is_either<wchar_t>(text[start_index+2], suffix3L, suffix3U));
}
///RV suffix functions
//-------------------------------------------------
///RV suffix comparison for one character
inline bool is_suffix_in_rv(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U)
{
if (text.length() < 1)
{
return false;
}
return (is_either<wchar_t>(text[text.length()-1], suffix1L, suffix1U) &&
(get_rv() <= text.length()-1) );
}
///RV suffix comparison for two characters
inline bool is_suffix_in_rv(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U)
{
if (text.length() < 2)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-2], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-1], suffix2L, suffix2U) ) &&
(get_rv() <= text.length()-2) );
}
///RV suffix comparison for three characters
inline bool is_suffix_in_rv(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U)
{
if (text.length() < 3)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-3], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-2], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-1], suffix3L, suffix3U) ) &&
(get_rv() <= text.length()-3) );
}
///RV suffix comparison for four characters
inline bool is_suffix_in_rv(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U)
{
if (text.length() < 4)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-4], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-3], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-2], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-1], suffix4L, suffix4U) ) &&
(get_rv() <= text.length()-4) );
}
///RV suffix comparison for five characters
inline bool is_suffix_in_rv(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U)
{
if (text.length() < 5)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-5], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-4], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-3], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-2], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-1], suffix5L, suffix5U) ) &&
(get_rv() <= text.length()-5) );
}
///RV suffix comparison for six characters
inline bool is_suffix_in_rv(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U)
{
if (text.length() < 6)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-6], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-5], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-4], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-3], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-2], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-1], suffix6L, suffix6U) ) &&
(get_rv() <= text.length()-6) );
}
///RV suffix comparison for seven characters
inline bool is_suffix_in_rv(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U,
const wchar_t suffix7L, const wchar_t suffix7U)
{
if (text.length() < 7)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-7], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-6], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-5], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-4], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-3], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-2], suffix6L, suffix6U) &&
is_either<wchar_t>(text[text.length()-1], suffix7L, suffix7U) ) &&
(get_rv() <= text.length()-7) );
}
///RV suffix comparison for eight characters
inline bool is_suffix_in_rv(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U,
const wchar_t suffix7L, const wchar_t suffix7U,
const wchar_t suffix8L, const wchar_t suffix8U)
{
if (text.length() < 8)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-8], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-7], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-6], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-5], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-4], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-3], suffix6L, suffix6U) &&
is_either<wchar_t>(text[text.length()-2], suffix7L, suffix7U) &&
is_either<wchar_t>(text[text.length()-1], suffix8L, suffix8U) ) &&
(get_rv() <= text.length()-8) );
}
///R1 suffix functions
//-------------------------------------------------
///R1 suffix comparison for one character
inline bool is_suffix_in_r1(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U)
{
if (text.length() < 1)
{
return false;
}
return (is_either<wchar_t>(text[text.length()-1], suffix1L, suffix1U) &&
(get_r1() <= text.length()-1) );
}
///R1 suffix comparison for two characters
inline bool is_suffix_in_r1(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U)
{
if (text.length() < 2)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-2], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-1], suffix2L, suffix2U) ) &&
(get_r1() <= text.length()-2) );
}
///R1 suffix comparison for three characters
inline bool is_suffix_in_r1(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U)
{
if (text.length() < 3)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-3], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-2], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-1], suffix3L, suffix3U) ) &&
(get_r1() <= text.length()-3) );
}
///R1 suffix comparison for four characters
inline bool is_suffix_in_r1(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U)
{
if (text.length() < 4)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-4], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-3], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-2], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-1], suffix4L, suffix4U) ) &&
(get_r1() <= text.length()-4) );
}
///R1 suffix comparison for five characters
inline bool is_suffix_in_r1(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U)
{
if (text.length() < 5)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-5], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-4], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-3], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-2], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-1], suffix5L, suffix5U) ) &&
(get_r1() <= text.length()-5) );
}
///R1 suffix comparison for six characters
inline bool is_suffix_in_r1(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U)
{
if (text.length() < 6)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-6], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-5], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-4], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-3], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-2], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-1], suffix6L, suffix6U) ) &&
(get_r1() <= text.length()-6) );
}
///R2 suffix functions
//-------------------------------------------------
///R2 suffix comparison for one character
inline bool is_suffix_in_r2(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U)
{
if (text.length() < 1)
{
return false;
}
return (is_either<wchar_t>(text[text.length()-1], suffix1L, suffix1U) &&
(get_r2() <= text.length()-1) );
}
///R2 suffix comparison for two characters
inline bool is_suffix_in_r2(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U)
{
if (text.length() < 2)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-2], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-1], suffix2L, suffix2U) ) &&
(get_r2() <= text.length()-2) );
}
///R2 suffix comparison for three characters
inline bool is_suffix_in_r2(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U)
{
if (text.length() < 3)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-3], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-2], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-1], suffix3L, suffix3U) ) &&
(get_r2() <= text.length()-3) );
}
///R2 suffix comparison for four characters
inline bool is_suffix_in_r2(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U)
{
if (text.length() < 4)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-4], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-3], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-2], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-1], suffix4L, suffix4U) ) &&
(get_r2() <= text.length()-4) );
}
///R2 suffix comparison for five characters
inline bool is_suffix_in_r2(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U)
{
if (text.length() < 5)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-5], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-4], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-3], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-2], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-1], suffix5L, suffix5U) ) &&
(get_r2() <= text.length()-5) );
}
///R2 suffix comparison for six characters
inline bool is_suffix_in_r2(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U)
{
if (text.length() < 6)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-6], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-5], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-4], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-3], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-2], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-1], suffix6L, suffix6U) ) &&
(get_r2() <= text.length()-6) );
}
///R2 suffix comparison for seven characters
inline bool is_suffix_in_r2(const string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U,
const wchar_t suffix7L, const wchar_t suffix7U)
{
if (text.length() < 7)
{
return false;
}
return ((is_either<wchar_t>(text[text.length()-7], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-6], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-5], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-4], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-3], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-2], suffix6L, suffix6U) &&
is_either<wchar_t>(text[text.length()-1], suffix7L, suffix7U) ) &&
(get_r2() <= text.length()-7) );
}
//suffix removal functions
//R1 deletion for one character suffix
inline bool delete_if_is_in_r1(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const bool success_on_find = true)
{
assert(suffix1L == string_util::tolower_western(suffix1U) );
if (text.length() < 1)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-1], suffix1L, suffix1U))
{
if (get_r1() <= text.length()-1)
{
text.erase(text.length()-1);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//R1 deletion for two character suffix
inline bool delete_if_is_in_r1(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const bool success_on_find = true)
{
if (text.length() < 2)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-2], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-1], suffix2L, suffix2U))
{
if (get_r1() <= text.length()-2)
{
text.erase(text.length()-2);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//R1 deletion for three character suffix
inline bool delete_if_is_in_r1(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const bool success_on_find = true)
{
if (text.length() < 3)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-3], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-2], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-1], suffix3L, suffix3U) )
{
if (get_r1() <= text.length()-3)
{
text.erase(text.length()-3);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//R1 deletion for four character suffix
inline bool delete_if_is_in_r1(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const bool success_on_find = true)
{
if (text.length() < 4)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-4], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-3], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-2], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-1], suffix4L, suffix4U) )
{
if (get_r1() <= text.length()-4)
{
text.erase(text.length()-4);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//R1 deletion for five character suffix
inline bool delete_if_is_in_r1(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const bool success_on_find = true)
{
if (text.length() < 5)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-5], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-4], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-3], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-2], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-1], suffix5L, suffix5U) )
{
if (get_r1() <= text.length()-5)
{
text.erase(text.length()-5);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//R1 deletion for six character suffix
inline bool delete_if_is_in_r1(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U,
const bool success_on_find = true)
{
if (text.length() < 6)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-6], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-5], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-4], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-3], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-2], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-1], suffix6L, suffix6U) )
{
if (get_r1() <= text.length()-6)
{
text.erase(text.length()-6);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//R1 deletion for seven character suffix
inline bool delete_if_is_in_r1(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U,
const wchar_t suffix7L, const wchar_t suffix7U,
const bool success_on_find = true)
{
if (text.length() < 7)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-7], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-6], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-5], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-4], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-3], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-2], suffix6L, suffix6U) &&
is_either<wchar_t>(text[text.length()-1], suffix7L, suffix7U) )
{
if (get_r1() <= text.length()-7)
{
text.erase(text.length()-7);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//R2 deletion functions
//R2 deletion for one character suffix
inline bool delete_if_is_in_r2(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const bool success_on_find = true)
{
if (text.length() < 1)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-1], suffix1L, suffix1U))
{
if (get_r2() <= text.length()-1)
{
text.erase(text.length()-1);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//R2 deletion for two character suffix
inline bool delete_if_is_in_r2(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const bool success_on_find = true)
{
if (text.length() < 2)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-2], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-1], suffix2L, suffix2U))
{
if (get_r2() <= text.length()-2)
{
text.erase(text.length()-2);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//R2 deletion for three character suffix
inline bool delete_if_is_in_r2(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const bool success_on_find = true)
{
if (text.length() < 3)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-3], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-2], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-1], suffix3L, suffix3U) )
{
if (get_r2() <= text.length()-3)
{
text.erase(text.length()-3);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//R2 deletion for four character suffix
inline bool delete_if_is_in_r2(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const bool success_on_find = true)
{
if (text.length() < 4)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-4], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-3], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-2], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-1], suffix4L, suffix4U) )
{
if (get_r2() <= text.length()-4)
{
text.erase(text.length()-4);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
///R2 deletion for five character suffix
inline bool delete_if_is_in_r2(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const bool success_on_find = true)
{
if (text.length() < 5)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-5], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-4], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-3], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-2], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-1], suffix5L, suffix5U) )
{
if (get_r2() <= text.length()-5)
{
text.erase(text.length()-5);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
///R2 deletion for six character suffix
inline bool delete_if_is_in_r2(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U,
const bool success_on_find = true)
{
if (text.length() < 6)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-6], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-5], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-4], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-3], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-2], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-1], suffix6L, suffix6U) )
{
if (get_r2() <= text.length()-6)
{
text.erase(text.length()-6);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
///R2 deletion for seven character suffix
inline bool delete_if_is_in_r2(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U,
const wchar_t suffix7L, const wchar_t suffix7U,
const bool success_on_find = true)
{
if (text.length() < 7)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-7], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-6], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-5], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-4], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-3], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-2], suffix6L, suffix6U) &&
is_either<wchar_t>(text[text.length()-1], suffix7L, suffix7U) )
{
if (get_r2() <= text.length()-7)
{
text.erase(text.length()-7);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
///R2 deletion for eight character suffix
inline bool delete_if_is_in_r2(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U,
const wchar_t suffix7L, const wchar_t suffix7U,
const wchar_t suffix8L, const wchar_t suffix8U,
const bool success_on_find = true)
{
if (text.length() < 8)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-8], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-7], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-6], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-5], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-4], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-3], suffix6L, suffix6U) &&
is_either<wchar_t>(text[text.length()-2], suffix7L, suffix7U) &&
is_either<wchar_t>(text[text.length()-1], suffix8L, suffix8U) )
{
if (get_r2() <= text.length()-8)
{
text.erase(text.length()-8);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//RV deletion functions
//RV deletion for one character suffix
inline bool delete_if_is_in_rv(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const bool success_on_find = true)
{
if (text.length() < 1)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-1], suffix1L, suffix1U))
{
if (get_rv() <= text.length()-1)
{
text.erase(text.length()-1);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//RV deletion for two character suffix
inline bool delete_if_is_in_rv(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const bool success_on_find = true)
{
if (text.length() < 2)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-2], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-1], suffix2L, suffix2U))
{
if (get_rv() <= text.length()-2)
{
text.erase(text.length()-2);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//RV deletion for three character suffix
inline bool delete_if_is_in_rv(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const bool success_on_find = true)
{
if (text.length() < 3)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-3], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-2], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-1], suffix3L, suffix3U) )
{
if (get_rv() <= text.length()-3)
{
text.erase(text.length()-3);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//RV deletion for four character suffix
inline bool delete_if_is_in_rv(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const bool success_on_find = true)
{
if (text.length() < 4)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-4], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-3], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-2], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-1], suffix4L, suffix4U) )
{
if (get_rv() <= text.length()-4)
{
text.erase(text.length()-4);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//RV deletion for five character suffix
inline bool delete_if_is_in_rv(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const bool success_on_find = true)
{
if (text.length() < 5)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-5], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-4], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-3], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-2], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-1], suffix5L, suffix5U) )
{
if (get_rv() <= text.length()-5)
{
text.erase(text.length()-5);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//RV deletion for six character suffix
inline bool delete_if_is_in_rv(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U,
const bool success_on_find = true)
{
if (text.length() < 6)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-6], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-5], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-4], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-3], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-2], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-1], suffix6L, suffix6U) )
{
if (get_rv() <= text.length()-6)
{
text.erase(text.length()-6);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//RV deletion for seven character suffix
inline bool delete_if_is_in_rv(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U,
const wchar_t suffix7L, const wchar_t suffix7U,
const bool success_on_find = true)
{
if (text.length() < 7)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-7], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-6], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-5], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-4], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-3], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-2], suffix6L, suffix6U) &&
is_either<wchar_t>(text[text.length()-1], suffix7L, suffix7U) )
{
if (get_rv() <= text.length()-7)
{
text.erase(text.length()-7);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//RV deletion for eight character suffix
inline bool delete_if_is_in_rv(string_typeT& text,
const wchar_t suffix1L, const wchar_t suffix1U,
const wchar_t suffix2L, const wchar_t suffix2U,
const wchar_t suffix3L, const wchar_t suffix3U,
const wchar_t suffix4L, const wchar_t suffix4U,
const wchar_t suffix5L, const wchar_t suffix5U,
const wchar_t suffix6L, const wchar_t suffix6U,
const wchar_t suffix7L, const wchar_t suffix7U,
const wchar_t suffix8L, const wchar_t suffix8U,
const bool success_on_find = true)
{
if (text.length() < 8)
{
return false;
}
if (is_either<wchar_t>(text[text.length()-8], suffix1L, suffix1U) &&
is_either<wchar_t>(text[text.length()-7], suffix2L, suffix2U) &&
is_either<wchar_t>(text[text.length()-6], suffix3L, suffix3U) &&
is_either<wchar_t>(text[text.length()-5], suffix4L, suffix4U) &&
is_either<wchar_t>(text[text.length()-4], suffix5L, suffix5U) &&
is_either<wchar_t>(text[text.length()-3], suffix6L, suffix6U) &&
is_either<wchar_t>(text[text.length()-2], suffix7L, suffix7U) &&
is_either<wchar_t>(text[text.length()-1], suffix8L, suffix8U) )
{
if (get_rv() <= text.length()-8)
{
text.erase(text.length()-8);
update_r_sections(text);
return true;
}
return success_on_find;
}
else
{
return false;
}
}
//string support functions
void remove_german_umlauts(string_typeT& text)
{
for (size_t i = 0; i < text.length(); ++i)
{
if (text[i] == 0xC4)
{
text[i] = UPPER_A;
}
else if (text[i] == 0xD6)
{
text[i] = UPPER_O;
}
else if (text[i] == 0xDC)
{
text[i] = UPPER_U;
}
else if (text[i] == 0xE4 )
{
text[i] = LOWER_A;
}
else if (text[i] == 0xF6)
{
text[i] = LOWER_O;
}
else if (text[i] == 0xFC)
{
text[i] = LOWER_U;
}
}
}
void italian_acutes_to_graves(string_typeT& text)
{
for (size_t i = 0; i < text.length(); ++i)
{
if (text[i] == 0xC1)//A acute
{
text[i] = 0xC0;
}
else if (text[i] == 0xC9)//E acute
{
text[i] = 0xC8;
}
else if (text[i] == 0xCD)//I acute
{
text[i] = 0xCC;
}
else if (text[i] == 0xD3)//O acute
{
text[i] = 0xD2;
}
else if (text[i] == 0xDA)//U acute
{
text[i] = 0xD9;
}
else if (text[i] == 0xE1)//a acute
{
text[i] = 0xE0;
}
else if (text[i] == 0xE9)//e acute
{
text[i] = 0xE8;
}
else if (text[i] == 0xED)//i acute
{
text[i] = 0xEC;
}
else if (text[i] == 0xF3)//o acute
{
text[i] = 0xF2;
}
else if (text[i] == 0xFA)//u acute
{
text[i] = 0xF9;
}
}
}
///Hash initial y, y after a vowel, and i between vowels into hashed character.
//----------------------------------------------------------
void hash_dutch_yi(string_typeT& text,
const wchar_t* vowel_string)
{
//need at least 2 letters for hashing
if (text.length() < 2)
{ return; }
if (text[0] == LOWER_Y)
{
text[0] = LOWER_Y_HASH;
}
else if (text[0] == UPPER_Y)
{
text[0] = UPPER_Y_HASH;
}
bool in_vowel_block = string_util::is_one_of(text[0], vowel_string);
size_t i = 1;
for (i = 1; i < text.length()-1; ++i)
{
if (in_vowel_block &&
text[i] == LOWER_I &&
string_util::is_one_of(text[i+1], vowel_string) )
{
text[i] = LOWER_I_HASH;
in_vowel_block = false;
}
else if (in_vowel_block &&
text[i] == UPPER_I &&
string_util::is_one_of(text[i+1], vowel_string) )
{
text[i] = UPPER_I_HASH;
in_vowel_block = false;
}
else if (in_vowel_block &&
text[i] == LOWER_Y)
{
text[i] = LOWER_Y_HASH;
in_vowel_block = false;
}
else if (in_vowel_block &&
text[i] == UPPER_Y)
{
text[i] = UPPER_Y_HASH;
in_vowel_block = false;
}
else if (string_util::is_one_of(text[i], vowel_string) )
{
in_vowel_block = true;
}
else
{
in_vowel_block = false;
}
}
//check the last letter
if (in_vowel_block &&
text[i] == LOWER_Y)
{
text[i] = LOWER_Y_HASH;
in_vowel_block = false;
}
else if (in_vowel_block &&
text[i] == UPPER_Y)
{
text[i] = UPPER_Y_HASH;
in_vowel_block = false;
}
}
//----------------------------------------------------------
inline void unhash_dutch_yi(string_typeT& text)
{
string_util::replace_all<wchar_t, string_typeT >(text, LOWER_Y_HASH, LOWER_Y);
string_util::replace_all<wchar_t, string_typeT >(text, UPPER_Y_HASH, UPPER_Y);
string_util::replace_all<wchar_t, string_typeT >(text, LOWER_I_HASH, LOWER_I);
string_util::replace_all<wchar_t, string_typeT >(text, UPPER_I_HASH, UPPER_I);
}
///Hash 'u' and 'y' between vowels
//----------------------------------------------------------
void hash_german_yu(string_typeT& text,
const wchar_t* vowel_string)
{
//need at least 2 letters for hashing
if (text.length() < 2)
{ return; }
bool in_vowel_block = string_util::is_one_of(text[0], vowel_string);
for (size_t i = 1; i < text.length()-1; ++i)
{
if (in_vowel_block &&
string_util::is_one_of(text[i], vowel_string) &&
string_util::is_one_of(text[i+1], vowel_string) )
{
if (text[i] == LOWER_Y)
{
text[i] = LOWER_Y_HASH;
}
else if (text[i] == UPPER_Y)
{
text[i] = UPPER_Y_HASH;
}
else if (text[i] == LOWER_U)
{
text[i] = LOWER_U_HASH;
}
else if (text[i] == UPPER_U)
{
text[i] = UPPER_U_HASH;
}
}
else if (string_util::is_one_of(text[i], vowel_string) )
{
in_vowel_block = true;
}
else
{
in_vowel_block = false;
}
}
//hashable values must be between vowels, so don't bother looking at last letter
}
//----------------------------------------------------------
inline void unhash_german_yu(string_typeT& text)
{
string_util::replace_all<wchar_t, string_typeT >(text, LOWER_Y_HASH, LOWER_Y);
string_util::replace_all<wchar_t, string_typeT >(text, UPPER_Y_HASH, UPPER_Y);
string_util::replace_all<wchar_t, string_typeT >(text, LOWER_U_HASH, LOWER_U);
string_util::replace_all<wchar_t, string_typeT >(text, UPPER_U_HASH, UPPER_U);
}
/**Hash u or i preceded and followed by a vowel, and y preceded or followed by a vowel.
u after q is also hashed. For example,
jouer -> joUer
ennuie -> ennuIe
yeux -> Yeux
quand -> qUand*/
//----------------------------------------------------------
void hash_french_yui(string_typeT& text,
const wchar_t* vowel_string)
{
//need at least 2 letters for hashing
if (text.length() < 2)
{ return; }
bool in_vowel_block = false;
//start loop at zero because 'y' at start of string can be hashed
size_t i = 0;
for (i = 0; i < text.length()-1; ++i)
{
if (in_vowel_block &&
string_util::is_one_of(text[i], vowel_string) &&
string_util::is_one_of(text[i+1], vowel_string) )
{
if (text[i] == LOWER_Y)
{
text[i] = LOWER_Y_HASH;
in_vowel_block = false;
}
else if (text[i] == UPPER_Y)
{
text[i] = UPPER_Y_HASH;
in_vowel_block = false;
}
else if (text[i] == LOWER_U)
{
text[i] = LOWER_U_HASH;
in_vowel_block = false;
}
else if (text[i] == UPPER_U)
{
text[i] = UPPER_U_HASH;
in_vowel_block = false;
}
else if (text[i] == LOWER_I)
{
text[i] = LOWER_I_HASH;
in_vowel_block = false;
}
else if (text[i] == UPPER_I)
{
text[i] = UPPER_I_HASH;
in_vowel_block = false;
}
}
//if just previous letter is a vowel then examine for 'y'
else if (in_vowel_block &&
text[i] == LOWER_Y)
{
text[i] = LOWER_Y_HASH;
in_vowel_block = false;
}
else if (in_vowel_block &&
text[i] == UPPER_Y)
{
text[i] = UPPER_Y_HASH;
in_vowel_block = false;
}
//if just following letter is a vowel then examine for 'y'
else if (text[i] == LOWER_Y &&
string_util::is_one_of(text[i+1], vowel_string) &&
is_neither<wchar_t>(text[i+1], LOWER_Y, UPPER_Y) )
{
text[i] = LOWER_Y_HASH;
in_vowel_block = false;
}
else if (text[i] == UPPER_Y &&
string_util::is_one_of(text[i+1], vowel_string) &&
is_neither<wchar_t>(text[i+1], LOWER_Y, UPPER_Y) )
{
text[i] = UPPER_Y_HASH;
in_vowel_block = false;
}
else if (string_util::is_one_of(text[i], vowel_string) )
{
if (text[i] == LOWER_U &&
(i > 0) &&
is_either<wchar_t>(text[i-1], LOWER_Q, UPPER_Q) )
{
text[i] = LOWER_U_HASH;
in_vowel_block = false;
}
else if (text[i] == UPPER_U &&
(i > 0) &&
is_either<wchar_t>(text[i-1], LOWER_Q, UPPER_Q) )
{
text[i] = UPPER_U_HASH;
in_vowel_block = false;
}
else
{
in_vowel_block = true;
}
}
else
{
in_vowel_block = false;
}
}
//verify that the last letter
if (text[i] == LOWER_Y &&
(i > 0) &&
string_util::is_one_of(text[i-1], vowel_string) )
{
text[i] = LOWER_Y_HASH;
}
else if (text[i] == UPPER_Y &&
(i > 0) &&
string_util::is_one_of(text[i-1], vowel_string) )
{
text[i] = UPPER_Y_HASH;
}
else if (text[i] == LOWER_U &&
(i > 0) &&
is_either<wchar_t>(text[i-1], LOWER_Q, UPPER_Q) )
{
text[i] = LOWER_U_HASH;
}
else if (text[i] == UPPER_U &&
(i > 0) &&
is_either<wchar_t>(text[i-1], LOWER_Q, UPPER_Q) )
{
text[i] = UPPER_U_HASH;
}
}
void unhash_french_yui(string_typeT& text)
{
string_util::replace_all<wchar_t, string_typeT >(text, LOWER_Y_HASH, LOWER_Y);
string_util::replace_all<wchar_t, string_typeT >(text, UPPER_Y_HASH, UPPER_Y);
string_util::replace_all<wchar_t, string_typeT >(text, LOWER_U_HASH, LOWER_U);
string_util::replace_all<wchar_t, string_typeT >(text, UPPER_U_HASH, UPPER_U);
string_util::replace_all<wchar_t, string_typeT >(text, LOWER_I_HASH, LOWER_I);
string_util::replace_all<wchar_t, string_typeT >(text, UPPER_I_HASH, UPPER_I);
}
//----------------------------------------------------------
void hash_y(string_typeT& text,
const wchar_t* vowel_string)
{
//need at least 2 letters for hashing
if (text.length() < 2)
{ return; }
//if first letter is a 'y', then it is likely not a vowel
if (text[0] == LOWER_Y)
{
text[0] = LOWER_Y_HASH;
}
else if (text[0] == UPPER_Y)
{
text[0] = UPPER_Y_HASH;
}
bool in_vowel_block = string_util::is_one_of(text[0], vowel_string);
for (size_t i = 1; i < text.length(); ++i)
{
//LOWER_Y after vowel is a consonant
if (in_vowel_block &&
text[i] == LOWER_Y)
{
text[i] = LOWER_Y_HASH;
in_vowel_block = false;
}
else if (in_vowel_block &&
text[i] == UPPER_Y)
{
text[i] = UPPER_Y_HASH;
in_vowel_block = false;
}
else if (string_util::is_one_of(text[i], vowel_string) )
{
in_vowel_block = true;
}
//we are on a consonant
else
{
in_vowel_block = false;
}
}
}
//----------------------------------------------------------
inline void unhash_y(string_typeT& text)
{
string_util::replace_all<wchar_t, string_typeT >(text, LOWER_Y_HASH, LOWER_Y);
string_util::replace_all<wchar_t, string_typeT >(text, UPPER_Y_HASH, UPPER_Y);
}
///Hash u after q, and u, i between vowels
//----------------------------------------------------------
void hash_italian_ui(string_typeT& text,
const wchar_t* vowel_string)
{
//need at least 2 letters for hashing
if (text.length() < 2)
{ return; }
bool in_vowel_block = string_util::is_one_of(text[0], vowel_string);
size_t i = 1;
for (i = 1; i < text.length()-1; ++i)
{
if (in_vowel_block &&
string_util::is_one_of(text[i], vowel_string) &&
string_util::is_one_of(text[i+1], vowel_string) )
{
if (text[i] == LOWER_I )
{
text[i] = LOWER_I_HASH;
}
else if (text[i] == UPPER_I )
{
text[i] = UPPER_I_HASH;
}
else if (text[i] == LOWER_U)
{
text[i] = LOWER_U_HASH;
}
else if (text[i] == UPPER_U)
{
text[i] = UPPER_U_HASH;
}
}
else if (string_util::is_one_of(text[i], vowel_string) )
{
/*u after q should be encrypted and not be
treated as a vowel*/
if (text[i] == LOWER_U &&
(i > 0) &&
is_either<wchar_t>(text[i-1], LOWER_Q, UPPER_Q) )
{
text[i] = LOWER_U_HASH;
in_vowel_block = false;
}
else if (text[i] == UPPER_U &&
(i > 0) &&
is_either<wchar_t>(text[i-1], LOWER_Q, UPPER_Q) )
{
text[i] = UPPER_U_HASH;
in_vowel_block = false;
}
else
{
in_vowel_block = true;
}
}
//we are on a consonant
else
{
in_vowel_block = false;
}
}
//verify the last letter
if (text[i] == LOWER_U &&
(i > 0) &&
is_either<wchar_t>(text[i-1], LOWER_Q, UPPER_Q) )
{
text[i] = LOWER_U_HASH;
}
else if (text[i] == UPPER_U &&
(i > 0) &&
is_either<wchar_t>(text[i-1], LOWER_Q, UPPER_Q) )
{
text[i] = UPPER_U_HASH;
}
}
//----------------------------------------------------------
inline void unhash_italian_ui(string_typeT& text)
{
string_util::replace_all<wchar_t, string_typeT >(text, LOWER_I_HASH, LOWER_I);
string_util::replace_all<wchar_t, string_typeT >(text, UPPER_I_HASH, UPPER_I);
string_util::replace_all<wchar_t, string_typeT >(text, LOWER_U_HASH, LOWER_U);
string_util::replace_all<wchar_t, string_typeT >(text, UPPER_U_HASH, UPPER_U);
}
//----------------------------------------------------------
void remove_dutch_umlauts(string_typeT& text)
{
for (size_t i = 0; i < text.length(); ++i)
{
if (text[i] == 0xC4)
{
text[i] = UPPER_A;
}
else if (text[i] == 0xCB)
{
text[i] = UPPER_E;
}
else if (text[i] == 0xCF)
{
text[i] = UPPER_I;
}
else if (text[i] == 0xD6)
{
text[i] = UPPER_O;
}
else if (text[i] == 0xDC)
{
text[i] = UPPER_U;
}
else if (text[i] == 0xE4)
{
text[i] = LOWER_A;
}
else if (text[i] == 0xEB)
{
text[i] = LOWER_E;
}
else if (text[i] == 0xEF)
{
text[i] = LOWER_I;
}
else if (text[i] == 0xF6)
{
text[i] = LOWER_O;
}
else if (text[i] == 0xFC)
{
text[i] = LOWER_U;
}
}
}
//----------------------------------------------------------
void remove_dutch_acutes(string_typeT& text)
{
for (size_t i = 0; i < text.length(); ++i)
{
if (text[i] == 0xC1)
{
text[i] = UPPER_A;
}
else if (text[i] == 0xC9)
{
text[i] = UPPER_E;
}
else if (text[i] == 0xCD)
{
text[i] = UPPER_I;
}
else if (text[i] == 0xD3)
{
text[i] = UPPER_O;
}
else if (text[i] == 0xDA)
{
text[i] = UPPER_U;
}
else if (text[i] == 0xE1)
{
text[i] = LOWER_A;
}
else if (text[i] == 0xE9)
{
text[i] = LOWER_E;
}
else if (text[i] == 0xED)
{
text[i] = LOWER_I;
}
else if (text[i] == 0xF3)
{
text[i] = LOWER_O;
}
else if (text[i] == 0xFA)
{
text[i] = LOWER_U;
}
}
}
//----------------------------------------------------------
void remove_spanish_acutes(string_typeT& text)
{
for (size_t i = 0; i < text.length(); ++i)
{
if (text[i] == 0xC1)
{
text[i] = UPPER_A;
}
else if (text[i] == 0xC9)
{
text[i] = UPPER_E;
}
else if (text[i] == 0xCD)
{
text[i] = UPPER_I;
}
else if (text[i] == 0xD3)
{
text[i] = UPPER_O;
}
else if (text[i] == 0xDA)
{
text[i] = UPPER_U;
}
else if (text[i] == 0xE1)
{
text[i] = LOWER_A;
}
else if (text[i] == 0xE9)
{
text[i] = LOWER_E;
}
else if (text[i] == 0xED)
{
text[i] = LOWER_I;
}
else if (text[i] == 0xF3)
{
text[i] = LOWER_O;
}
else if (text[i] == 0xFA)
{
text[i] = LOWER_U;
}
}
}
inline size_t get_r1() const
{ return m_r1; }
inline void set_r1(const size_t val)
{ m_r1 = val; }
inline size_t get_r2() const
{ return m_r2; }
inline void set_r2(const size_t val)
{ m_r2 = val; }
inline size_t get_rv() const
{ return m_rv; }
inline void set_rv(const size_t val)
{ m_rv = val; }
void reset_r_values()
{ m_r1 = m_r2 = m_rv = 0; }
private:
size_t m_r1;
size_t m_r2;
//only used for romance/russian languages
size_t m_rv;
};
//------------------------------------------------------
/*A non-operational stemmer that is used in place of regular stemmers when
you don't want the system to actually stem anything.*/
template <typename string_typeT = std::wstring>
class no_op_stem
{
public:
///No-op stemming of declared string type
inline void operator()(const string_typeT& text) const
{}
///No-op stemming of flexible string type
template <typename T>
inline void operator()(const T& text) const
{}
};
}
#endif //__STEM_H__
| [
"caoy11@foxmail.com"
] | caoy11@foxmail.com |
6a5d1a2ec37880fcf4e37edc0ade4d109421b3d4 | 2b71f9562f48985c0ac78c0addd90518b2b38d9d | /Exàmens/2019/recuperació/P34239-Suma_màxima.cc | b486538d0dc90e21acb81b4dc60ef1ccad9d3ab6 | [] | no_license | delefme/jutge-informatica | ed05fdd1aa8d95847022dc6cb847749b5817e907 | 4fc45bee293708074b35a62b2a43af44c66092c0 | refs/heads/master | 2023-08-13T17:47:02.779225 | 2020-08-08T22:16:24 | 2020-08-08T22:16:24 | 286,070,634 | 10 | 4 | null | 2021-09-23T19:55:18 | 2020-08-08T15:36:29 | C++ | UTF-8 | C++ | false | false | 446 | cc | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int abs(int x) {
if (x < 0) return -x;
return x;
}
int main() {
int n, d;
while (cin >> n >> d) {
vector<int> v(n);
for (int i = 0; i < n; i++) cin >> v[i];
sort(v.begin(), v.end());
int suma = v[n-1];
int ultim = n-1;
for (int i = n-2; i >= 0; i--) {
if (abs(v[i] - v[ultim]) >= d) {suma += v[i]; ultim = i;}
}
cout << suma << endl;
}
}
| [
"andreuhuguet@gmail.com"
] | andreuhuguet@gmail.com |
f0f2bc83cb16db4cddfa2c3134b32e0e7ad03ef3 | 82b6551a79786cbe0727b8b8473bc69d11260cec | /Exception.cpp | 6f83ec4a0b6d57f12e6f0d4a26883ade1a228f99 | [] | no_license | lfxy/netframe | 831dddcf7e0b02b663a66e989214317b13249a66 | e11b3b0bf1fc9641884d97b03e0704259f251a79 | refs/heads/master | 2020-04-16T15:41:46.017639 | 2016-04-22T10:25:08 | 2016-04-22T10:25:08 | 32,329,060 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,004 | cpp | // Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com)
#include <Exception.h>
//#include <cxxabi.h>
#include <execinfo.h>
#include <stdlib.h>
Exception::Exception(const char* msg)
: message_(msg)
{
fillStackTrace();
}
Exception::Exception(const std::string& msg)
: message_(msg)
{
fillStackTrace();
}
Exception::~Exception() throw ()
{
}
const char* Exception::what() const throw()
{
return message_.c_str();
}
const char* Exception::stackTrace() const throw()
{
return stack_.c_str();
}
void Exception::fillStackTrace()
{
const int len = 200;
void* buffer[len];
int nptrs = ::backtrace(buffer, len);
char** strings = ::backtrace_symbols(buffer, nptrs);
if (strings)
{
for (int i = 0; i < nptrs; ++i)
{
// TODO demangle funcion name with abi::__cxa_demangle
stack_.append(strings[i]);
stack_.push_back('\n');
}
free(strings);
}
}
| [
"zhiqiang.cao@emc.com"
] | zhiqiang.cao@emc.com |
4c4ed686f582dbcc08758fc34bcabe993a648705 | 38698091bf4e8bd30685f0accd281b92507e6d5f | /advancedLighting/HDR-toneMapping/HDR2/toneMapping.cpp | 461db24ba5e34e3733d7cc6bee7a8c6448bd627c | [
"MIT"
] | permissive | Ron3/noteForOpenGL | 0e49a6c09d15e119c8058a7ca1ad84ff6782928e | c59e8b55d7cb17085a455fad6b6f300cfe500f0f | refs/heads/master | 2021-01-20T12:28:39.360336 | 2017-02-19T08:23:30 | 2017-02-19T08:23:30 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 14,213 | cpp | // 引入GLEW库 定义静态链接
#define GLEW_STATIC
#include <GLEW/glew.h>
// 引入GLFW库
#include <GLFW/glfw3.h>
// 引入SOIL库
#include <SOIL/SOIL.h>
// 引入GLM库
#include <GLM/glm.hpp>
#include <GLM/gtc/matrix_transform.hpp>
#include <GLM/gtc/type_ptr.hpp>
#include <iostream>
#include <vector>
#include <sstream>
// 包含着色器加载库
#include "shader.h"
// 包含相机控制辅助类
#include "camera.h"
// 包含纹理加载辅助类
#include "texture.h"
// 键盘回调函数原型声明
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods);
// 鼠标移动回调函数原型声明
void mouse_move_callback(GLFWwindow* window, double xpos, double ypos);
// 鼠标滚轮回调函数原型声明
void mouse_scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
// 场景中移动
void do_movement();
// 定义程序常量
const int WINDOW_WIDTH = 800, WINDOW_HEIGHT = 600;
// 用于相机交互参数
GLfloat lastX = WINDOW_WIDTH / 2.0f, lastY = WINDOW_HEIGHT / 2.0f;
bool firstMouseMove = true;
bool keyPressedStatus[1024]; // 按键情况记录
GLfloat deltaTime = 0.0f; // 当前帧和上一帧的时间差
GLfloat lastFrame = 0.0f; // 上一帧时间
Camera camera(glm::vec3(0.0f, 0.0f, 5.0f));
GLfloat exposureFactor = 1.0f;
GLuint CubeVAOId, CubeVBOId;
GLuint quadVAOId, quadVBOId;
GLuint sceneTextId;
void prepareVBO();
GLuint HDRTextId, HDRFBOId;
bool prepareHDRFBO(GLuint& HDRFBOId, GLuint& HDRTextId);
void renderScene(Shader& shader);
void renderAdjustedScene(Shader& shader);
int main(int argc, char** argv)
{
if (!glfwInit()) // 初始化glfw库
{
std::cout << "Error::GLFW could not initialize GLFW!" << std::endl;
return -1;
}
// 开启OpenGL 3.3 core profile
std::cout << "Start OpenGL core profile version 3.3" << std::endl;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
// 创建窗口
GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT,
"Demo of HDR-tone mapping(use up down change exposure)", NULL, NULL);
if (!window)
{
std::cout << "Error::GLFW could not create winddow!" << std::endl;
glfwTerminate();
return -1;
}
// 创建的窗口的context指定为当前context
glfwMakeContextCurrent(window);
// 注册窗口键盘事件回调函数
glfwSetKeyCallback(window, key_callback);
// 注册鼠标事件回调函数
glfwSetCursorPosCallback(window, mouse_move_callback);
// 注册鼠标滚轮事件回调函数
glfwSetScrollCallback(window, mouse_scroll_callback);
// 鼠标捕获 停留在程序内
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// 初始化GLEW 获取OpenGL函数
glewExperimental = GL_TRUE; // 让glew获取所有拓展函数
GLenum status = glewInit();
if (status != GLEW_OK)
{
std::cout << "Error::GLEW glew version:" << glewGetString(GLEW_VERSION)
<< " error string:" << glewGetErrorString(status) << std::endl;
glfwTerminate();
return -1;
}
// 设置视口参数
glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
// Section1 准备顶点数据
prepareVBO();
prepareHDRFBO(HDRFBOId, HDRTextId);
// Section2 加载纹理
sceneTextId = TextureHelper::load2DTexture("../../resources/textures/wood.png");
// Section3 准备着色器程序
Shader shader("scene.vertex", "scene.frag");
Shader HDRShader("hdrAdjust.vertex", "hdrAdjust.frag");
// Section4 准备光源数据
struct LightAttr
{
LightAttr(glm::vec3 pos, glm::vec3 diff, glm::vec3 spec)
{
position = pos;
diffuse = diff;
specular = spec;
}
glm::vec3 position;
glm::vec3 diffuse;
glm::vec3 specular;
};
std::vector<LightAttr> seqLightAttr;
seqLightAttr.push_back(LightAttr(glm::vec3(0.0f, 0.0f, 49.5f),
glm::vec3(200.0f / 5.0f, 200.0f / 5.0f, 200.0f / 5.0f),
glm::vec3(200.0f, 200.0f, 200.0f)));
seqLightAttr.push_back(LightAttr(glm::vec3(-1.4f, -1.9f, 9.0f),
glm::vec3(0.1f / 5.0f, 0.0f, 0.0f),
glm::vec3(0.1f, 0.0f, 0.0f)));
seqLightAttr.push_back(LightAttr(glm::vec3(0.0f, -1.8f, 4.0f),
glm::vec3(0.0f, 0.0f, 0.2f / 5.0f),
glm::vec3(0.0f, 0.0f, 0.2f)));
seqLightAttr.push_back(LightAttr(glm::vec3(0.8f, -1.7f, 6.0f),
glm::vec3(0.0f, 0.1f / 5.0f, 0.0f),
glm::vec3(0.0f, 0.1f, 0.0f)));
glEnable(GL_DEPTH_TEST);
// 开始游戏主循环
while (!glfwWindowShouldClose(window))
{
GLfloat currentFrame = (GLfloat)glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
glfwPollEvents(); // 处理例如鼠标 键盘等事件
do_movement(); // 根据用户操作情况 更新相机属性
glm::mat4 projection = glm::perspective(camera.mouse_zoom,
(GLfloat)(WINDOW_WIDTH) / WINDOW_HEIGHT, 1.0f, 100.0f); // 投影矩阵
glm::mat4 view = camera.getViewMatrix(); // 视变换矩阵
// 这里填写场景绘制代码
glm::mat4 model = glm::mat4();
// 第一遍 绘制场景到HDR Frame buffer
glBindFramebuffer(GL_FRAMEBUFFER, HDRFBOId);
shader.use();
// 清除颜色缓冲区 重置为指定颜色
glClearColor(0.18f, 0.04f, 0.14f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// 设置光源属性
for (size_t i = 0; i < seqLightAttr.size(); ++i)
{
std::stringstream strStream;
strStream << "lights[" << i << "]";
std::string indexStr = strStream.str();
glUniform3fv(glGetUniformLocation(shader.programId,
(indexStr + ".diffuse").c_str()), 1, glm::value_ptr(seqLightAttr[i].diffuse));
glUniform3fv(glGetUniformLocation(shader.programId,
(indexStr + ".specular").c_str()), 1, glm::value_ptr(seqLightAttr[i].specular));
glUniform3fv(glGetUniformLocation(shader.programId,
(indexStr + ".position").c_str()), 1, glm::value_ptr(seqLightAttr[i].position));
}
// 设置观察者位置
GLint viewPosLoc = glGetUniformLocation(shader.programId, "viewPos");
glUniform3f(viewPosLoc, camera.position.x, camera.position.y, camera.position.z);
// 设置变换矩阵
glUniformMatrix4fv(glGetUniformLocation(shader.programId, "projection"),
1, GL_FALSE, glm::value_ptr(projection));
glUniformMatrix4fv(glGetUniformLocation(shader.programId, "view"),
1, GL_FALSE, glm::value_ptr(view));
model = glm::mat4();
model = glm::translate(model, glm::vec3(0.0f, 0.0f, 25.0));
model = glm::scale(model, glm::vec3(5.0f, 5.0f, 55.0f));
glUniformMatrix4fv(glGetUniformLocation(shader.programId, "model"), 1, GL_FALSE, glm::value_ptr(model));
glUniform1i(glGetUniformLocation(shader.programId, "inverse_normals"), GL_TRUE);
renderScene(shader);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// 第二遍 调整HDR中color buffer 绘制到平面上
glClearColor(0.18f, 0.04f, 0.14f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
HDRShader.use();
glUniform1f(glGetUniformLocation(HDRShader.programId, "exposureFactor"), exposureFactor);
renderAdjustedScene(HDRShader);
glBindVertexArray(0);
glUseProgram(0);
glfwSwapBuffers(window); // 交换缓存
}
// 释放资源
glDeleteVertexArrays(1, &quadVAOId);
glDeleteBuffers(1, &quadVBOId);
glfwTerminate();
return 0;
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key >= 0 && key < 1024)
{
if (action == GLFW_PRESS)
keyPressedStatus[key] = true;
else if (action == GLFW_RELEASE)
keyPressedStatus[key] = false;
}
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, GL_TRUE); // 关闭窗口
}
else if (key == GLFW_KEY_UP && action == GLFW_PRESS)
{
exposureFactor += 0.1f;
std::cout << "exposure: " << exposureFactor << std::endl;
}
else if (key == GLFW_KEY_DOWN && action == GLFW_PRESS)
{
exposureFactor -= 0.1f;
std::cout << "exposure: " << exposureFactor << std::endl;
}
}
void mouse_move_callback(GLFWwindow* window, double xpos, double ypos)
{
if (firstMouseMove) // 首次鼠标移动
{
lastX = xpos;
lastY = ypos;
firstMouseMove = false;
}
GLfloat xoffset = xpos - lastX;
GLfloat yoffset = lastY - ypos;
lastX = xpos;
lastY = ypos;
camera.handleMouseMove(xoffset, yoffset);
}
// 由相机辅助类处理鼠标滚轮控制
void mouse_scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
camera.handleMouseScroll(yoffset);
}
// 由相机辅助类处理键盘控制
void do_movement()
{
if (keyPressedStatus[GLFW_KEY_W])
camera.handleKeyPress(FORWARD, deltaTime);
if (keyPressedStatus[GLFW_KEY_S])
camera.handleKeyPress(BACKWARD, deltaTime);
if (keyPressedStatus[GLFW_KEY_A])
camera.handleKeyPress(LEFT, deltaTime);
if (keyPressedStatus[GLFW_KEY_D])
camera.handleKeyPress(RIGHT, deltaTime);
}
void prepareVBO()
{
// 指定立方体顶点属性数据 顶点位置 法向量 纹理
GLfloat cubeVertices[] = {
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // A
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, // B
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // C
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // C
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, // D
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // A
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, // E
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0, 1.0f, // H
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, // G
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, // G
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, // F
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, // E
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // D
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0, 1.0f, // H
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // E
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // E
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // A
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // D
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // F
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // G
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // C
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // C
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,// B
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,// F
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, // G
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0, 1.0f, // H
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, // D
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, // D
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // C
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, // G
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, // A
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, // E
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, // F
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, // F
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, // B
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, // A
};
// 创建物体缓存对象
glGenVertexArrays(1, &CubeVAOId);
glBindVertexArray(CubeVAOId);
glGenBuffers(1, &CubeVBOId);
glBindBuffer(GL_ARRAY_BUFFER, CubeVBOId);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), cubeVertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
8 * sizeof(GL_FLOAT), (GLvoid*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE,
8 * sizeof(GL_FLOAT), (GLvoid*)(3 * sizeof(GL_FLOAT)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE,
8 * sizeof(GL_FLOAT), (GLvoid*)(6 * sizeof(GL_FLOAT)));
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// 指定用于展示的矩形顶点属性数据 位置 纹理
GLfloat quadVertices[] = {
-1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 0.0f, 0.0f,
1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
};
glGenVertexArrays(1, &quadVAOId);
glGenBuffers(1, &quadVBOId);
glBindVertexArray(quadVAOId);
glBindBuffer(GL_ARRAY_BUFFER, quadVBOId);
glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
5 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE,
5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
}
/*
* 准备HDR的FBO
*/
bool prepareHDRFBO(GLuint& HDRFBOId, GLuint& HDRTextId)
{
glGenFramebuffers(1, &HDRFBOId);
glBindFramebuffer(GL_FRAMEBUFFER, HDRFBOId);
// 创建color buffer 注意这里的格式需要指定 GL_RGB16F GL_RGBA16F 等这类浮点表示的存储
glGenTextures(1, &HDRTextId);
glBindTexture(GL_TEXTURE_2D, HDRTextId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGBA, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// 创建depth buffer
GLuint rboDepth;
glGenRenderbuffers(1, &rboDepth);
glBindRenderbuffer(GL_RENDERBUFFER, rboDepth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT,WINDOW_WIDTH, WINDOW_HEIGHT);
// 绑定buffer
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, HDRTextId, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rboDepth);
// 检查构建是否成功
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return false;
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return true;
}
void renderScene(Shader& shader)
{
glBindVertexArray(CubeVAOId);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, sceneTextId);
glUniform1i(glGetUniformLocation(shader.programId, "text"), 0);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindTexture(GL_TEXTURE_2D, 0);
glBindVertexArray(0);
}
void renderAdjustedScene(Shader& shader)
{
glBindVertexArray(quadVAOId);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, HDRTextId); // 使用浮点表示的颜色分量的HDR纹理
glUniform1i(glGetUniformLocation(shader.programId, "hdrText"), 0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glBindTexture(GL_TEXTURE_2D, 0);
glBindVertexArray(0);
} | [
"393524628@qq.com"
] | 393524628@qq.com |
87351728ad3d226d02eda82adfecd20888bd191d | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir521/dir3871/dir4221/dir4222/file4304.cpp | cae5c15284bd8f179160f3639fc85ab384a9d6dd | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 111 | cpp | #ifndef file4304
#error "macro file4304 must be defined"
#endif
static const char* file4304String = "file4304"; | [
"tgeng@google.com"
] | tgeng@google.com |
62306e5127e11ceac18f78b3351d53bcfeef0577 | 75933a7ef9c77ffb3a06a1cecde79205c2b327ab | /renderdoc/driver/d3d11/d3d11_serialise.cpp | ab6776610bc23a11b983b74c5ebace821e2aa4ca | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | gvvynplaine/renderdoc | 983aac678006942e938aa9599cc4d58b48e04e21 | efafd0b766ea88b8563c7911dd111cbd0c6ffd65 | refs/heads/v1.x | 2023-01-01T19:32:13.183376 | 2020-07-07T14:40:55 | 2020-07-07T17:15:09 | 278,307,900 | 0 | 0 | MIT | 2020-10-30T12:17:30 | 2020-07-09T08:30:17 | null | UTF-8 | C++ | false | false | 28,174 | cpp | /******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019-2020 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "common/common.h"
#include "serialise/serialiser.h"
#include "d3d11_common.h"
#include "d3d11_manager.h"
#include "d3d11_resources.h"
// serialisation of object handles via IDs.
template <class SerialiserType, class Interface>
void DoSerialiseViaResourceId(SerialiserType &ser, Interface *&el)
{
D3D11ResourceManager *rm = (D3D11ResourceManager *)ser.GetUserData();
ResourceId id;
if(ser.IsWriting() && rm)
id = GetIDForResource(el);
DoSerialise(ser, id);
if(ser.IsReading())
{
if(id != ResourceId() && rm && rm->HasLiveResource(id))
el = (Interface *)rm->GetLiveResource(id);
else
el = NULL;
}
}
#undef SERIALISE_INTERFACE
#define SERIALISE_INTERFACE(iface) \
template <class SerialiserType> \
void DoSerialise(SerialiserType &ser, iface *&el) \
{ \
DoSerialiseViaResourceId(ser, el); \
} \
INSTANTIATE_SERIALISE_TYPE(iface *);
SERIALISE_D3D_INTERFACES();
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_BUFFER_DESC &el)
{
SERIALISE_MEMBER(ByteWidth);
SERIALISE_MEMBER(Usage);
SERIALISE_MEMBER_TYPED(D3D11_BIND_FLAG, BindFlags);
SERIALISE_MEMBER_TYPED(D3D11_CPU_ACCESS_FLAG, CPUAccessFlags);
SERIALISE_MEMBER_TYPED(D3D11_RESOURCE_MISC_FLAG, MiscFlags);
SERIALISE_MEMBER(StructureByteStride);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEXTURE1D_DESC &el)
{
SERIALISE_MEMBER(Width);
SERIALISE_MEMBER(MipLevels);
SERIALISE_MEMBER(ArraySize);
SERIALISE_MEMBER(Format);
SERIALISE_MEMBER(Usage);
SERIALISE_MEMBER_TYPED(D3D11_BIND_FLAG, BindFlags);
SERIALISE_MEMBER_TYPED(D3D11_CPU_ACCESS_FLAG, CPUAccessFlags);
SERIALISE_MEMBER_TYPED(D3D11_RESOURCE_MISC_FLAG, MiscFlags);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEXTURE2D_DESC &el)
{
SERIALISE_MEMBER(Width);
SERIALISE_MEMBER(Height);
SERIALISE_MEMBER(MipLevels);
SERIALISE_MEMBER(ArraySize);
SERIALISE_MEMBER(Format);
SERIALISE_MEMBER(SampleDesc);
SERIALISE_MEMBER(Usage);
SERIALISE_MEMBER_TYPED(D3D11_BIND_FLAG, BindFlags);
SERIALISE_MEMBER_TYPED(D3D11_CPU_ACCESS_FLAG, CPUAccessFlags);
SERIALISE_MEMBER_TYPED(D3D11_RESOURCE_MISC_FLAG, MiscFlags);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEXTURE2D_DESC1 &el)
{
SERIALISE_MEMBER(Width);
SERIALISE_MEMBER(Height);
SERIALISE_MEMBER(MipLevels);
SERIALISE_MEMBER(ArraySize);
SERIALISE_MEMBER(Format);
SERIALISE_MEMBER(SampleDesc);
SERIALISE_MEMBER(Usage);
SERIALISE_MEMBER_TYPED(D3D11_BIND_FLAG, BindFlags);
SERIALISE_MEMBER_TYPED(D3D11_CPU_ACCESS_FLAG, CPUAccessFlags);
SERIALISE_MEMBER_TYPED(D3D11_RESOURCE_MISC_FLAG, MiscFlags);
SERIALISE_MEMBER(TextureLayout);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEXTURE3D_DESC &el)
{
SERIALISE_MEMBER(Width);
SERIALISE_MEMBER(Height);
SERIALISE_MEMBER(Depth);
SERIALISE_MEMBER(MipLevels);
SERIALISE_MEMBER(Format);
SERIALISE_MEMBER(Usage);
SERIALISE_MEMBER_TYPED(D3D11_BIND_FLAG, BindFlags);
SERIALISE_MEMBER_TYPED(D3D11_CPU_ACCESS_FLAG, CPUAccessFlags);
SERIALISE_MEMBER_TYPED(D3D11_RESOURCE_MISC_FLAG, MiscFlags);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEXTURE3D_DESC1 &el)
{
SERIALISE_MEMBER(Width);
SERIALISE_MEMBER(Height);
SERIALISE_MEMBER(Depth);
SERIALISE_MEMBER(MipLevels);
SERIALISE_MEMBER(Format);
SERIALISE_MEMBER(Usage);
SERIALISE_MEMBER_TYPED(D3D11_BIND_FLAG, BindFlags);
SERIALISE_MEMBER_TYPED(D3D11_CPU_ACCESS_FLAG, CPUAccessFlags);
SERIALISE_MEMBER_TYPED(D3D11_RESOURCE_MISC_FLAG, MiscFlags);
SERIALISE_MEMBER(TextureLayout);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_BUFFER_SRV &el)
{
SERIALISE_MEMBER(FirstElement);
SERIALISE_MEMBER(NumElements);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_BUFFEREX_SRV &el)
{
SERIALISE_MEMBER(FirstElement);
SERIALISE_MEMBER(NumElements);
SERIALISE_MEMBER_TYPED(D3D11_BUFFEREX_SRV_FLAG, Flags);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX1D_SRV &el)
{
SERIALISE_MEMBER(MostDetailedMip);
SERIALISE_MEMBER(MipLevels);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX1D_ARRAY_SRV &el)
{
SERIALISE_MEMBER(MostDetailedMip);
SERIALISE_MEMBER(MipLevels);
SERIALISE_MEMBER(FirstArraySlice);
SERIALISE_MEMBER(ArraySize);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2D_SRV &el)
{
SERIALISE_MEMBER(MostDetailedMip);
SERIALISE_MEMBER(MipLevels);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2D_ARRAY_SRV &el)
{
SERIALISE_MEMBER(MostDetailedMip);
SERIALISE_MEMBER(MipLevels);
SERIALISE_MEMBER(FirstArraySlice);
SERIALISE_MEMBER(ArraySize);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2D_SRV1 &el)
{
SERIALISE_MEMBER(MostDetailedMip);
SERIALISE_MEMBER(MipLevels);
SERIALISE_MEMBER(PlaneSlice);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2D_ARRAY_SRV1 &el)
{
SERIALISE_MEMBER(MostDetailedMip);
SERIALISE_MEMBER(MipLevels);
SERIALISE_MEMBER(FirstArraySlice);
SERIALISE_MEMBER(ArraySize);
SERIALISE_MEMBER(PlaneSlice);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX3D_SRV &el)
{
SERIALISE_MEMBER(MostDetailedMip);
SERIALISE_MEMBER(MipLevels);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEXCUBE_SRV &el)
{
SERIALISE_MEMBER(MostDetailedMip);
SERIALISE_MEMBER(MipLevels);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEXCUBE_ARRAY_SRV &el)
{
SERIALISE_MEMBER(MostDetailedMip);
SERIALISE_MEMBER(MipLevels);
SERIALISE_MEMBER(First2DArrayFace);
SERIALISE_MEMBER(NumCubes);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2DMS_SRV &el)
{
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2DMS_ARRAY_SRV &el)
{
SERIALISE_MEMBER(FirstArraySlice);
SERIALISE_MEMBER(ArraySize);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_SHADER_RESOURCE_VIEW_DESC &el)
{
SERIALISE_MEMBER(Format);
SERIALISE_MEMBER(ViewDimension);
switch(el.ViewDimension)
{
case D3D11_SRV_DIMENSION_UNKNOWN: break;
case D3D11_SRV_DIMENSION_BUFFER: SERIALISE_MEMBER(Buffer); break;
case D3D11_SRV_DIMENSION_TEXTURE1D: SERIALISE_MEMBER(Texture1D); break;
case D3D11_SRV_DIMENSION_TEXTURE1DARRAY: SERIALISE_MEMBER(Texture1DArray); break;
case D3D11_SRV_DIMENSION_TEXTURE2D: SERIALISE_MEMBER(Texture2D); break;
case D3D11_SRV_DIMENSION_TEXTURE2DARRAY: SERIALISE_MEMBER(Texture2DArray); break;
case D3D11_SRV_DIMENSION_TEXTURE2DMS: SERIALISE_MEMBER(Texture2DMS); break;
case D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY: SERIALISE_MEMBER(Texture2DMSArray); break;
case D3D11_SRV_DIMENSION_TEXTURE3D: SERIALISE_MEMBER(Texture3D); break;
case D3D11_SRV_DIMENSION_TEXTURECUBE: SERIALISE_MEMBER(TextureCube); break;
case D3D11_SRV_DIMENSION_TEXTURECUBEARRAY: SERIALISE_MEMBER(TextureCubeArray); break;
case D3D11_SRV_DIMENSION_BUFFEREX: SERIALISE_MEMBER(BufferEx); break;
default: RDCERR("Unrecognised SRV Dimension %d", el.ViewDimension); break;
}
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_SHADER_RESOURCE_VIEW_DESC1 &el)
{
SERIALISE_MEMBER(Format);
SERIALISE_MEMBER(ViewDimension);
switch(el.ViewDimension)
{
case D3D11_SRV_DIMENSION_UNKNOWN: break;
case D3D11_SRV_DIMENSION_BUFFER: SERIALISE_MEMBER(Buffer); break;
case D3D11_SRV_DIMENSION_TEXTURE1D: SERIALISE_MEMBER(Texture1D); break;
case D3D11_SRV_DIMENSION_TEXTURE1DARRAY: SERIALISE_MEMBER(Texture1DArray); break;
case D3D11_SRV_DIMENSION_TEXTURE2D: SERIALISE_MEMBER(Texture2D); break;
case D3D11_SRV_DIMENSION_TEXTURE2DARRAY: SERIALISE_MEMBER(Texture2DArray); break;
case D3D11_SRV_DIMENSION_TEXTURE2DMS: SERIALISE_MEMBER(Texture2DMS); break;
case D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY: SERIALISE_MEMBER(Texture2DMSArray); break;
case D3D11_SRV_DIMENSION_TEXTURE3D: SERIALISE_MEMBER(Texture3D); break;
case D3D11_SRV_DIMENSION_TEXTURECUBE: SERIALISE_MEMBER(TextureCube); break;
case D3D11_SRV_DIMENSION_TEXTURECUBEARRAY: SERIALISE_MEMBER(TextureCubeArray); break;
case D3D11_SRV_DIMENSION_BUFFEREX: SERIALISE_MEMBER(BufferEx); break;
default: RDCERR("Unrecognised SRV Dimension %d", el.ViewDimension); break;
}
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_BUFFER_RTV &el)
{
SERIALISE_MEMBER(FirstElement);
SERIALISE_MEMBER(NumElements);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX1D_RTV &el)
{
SERIALISE_MEMBER(MipSlice);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX1D_ARRAY_RTV &el)
{
SERIALISE_MEMBER(MipSlice);
SERIALISE_MEMBER(FirstArraySlice);
SERIALISE_MEMBER(ArraySize);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2D_RTV &el)
{
SERIALISE_MEMBER(MipSlice);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2D_ARRAY_RTV &el)
{
SERIALISE_MEMBER(MipSlice);
SERIALISE_MEMBER(FirstArraySlice);
SERIALISE_MEMBER(ArraySize);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2DMS_RTV &el)
{
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2DMS_ARRAY_RTV &el)
{
SERIALISE_MEMBER(FirstArraySlice);
SERIALISE_MEMBER(ArraySize);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2D_RTV1 &el)
{
SERIALISE_MEMBER(MipSlice);
SERIALISE_MEMBER(PlaneSlice);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2D_ARRAY_RTV1 &el)
{
SERIALISE_MEMBER(MipSlice);
SERIALISE_MEMBER(FirstArraySlice);
SERIALISE_MEMBER(ArraySize);
SERIALISE_MEMBER(PlaneSlice);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX3D_RTV &el)
{
SERIALISE_MEMBER(MipSlice);
SERIALISE_MEMBER(FirstWSlice);
SERIALISE_MEMBER(WSize);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_RENDER_TARGET_VIEW_DESC &el)
{
SERIALISE_MEMBER(Format);
SERIALISE_MEMBER(ViewDimension);
switch(el.ViewDimension)
{
case D3D11_RTV_DIMENSION_UNKNOWN: break;
case D3D11_RTV_DIMENSION_BUFFER: SERIALISE_MEMBER(Buffer); break;
case D3D11_RTV_DIMENSION_TEXTURE1D: SERIALISE_MEMBER(Texture1D); break;
case D3D11_RTV_DIMENSION_TEXTURE1DARRAY: SERIALISE_MEMBER(Texture1DArray); break;
case D3D11_RTV_DIMENSION_TEXTURE2D: SERIALISE_MEMBER(Texture2D); break;
case D3D11_RTV_DIMENSION_TEXTURE2DARRAY: SERIALISE_MEMBER(Texture2DArray); break;
case D3D11_RTV_DIMENSION_TEXTURE2DMS: SERIALISE_MEMBER(Texture2DMS); break;
case D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY: SERIALISE_MEMBER(Texture2DMSArray); break;
case D3D11_RTV_DIMENSION_TEXTURE3D: SERIALISE_MEMBER(Texture3D); break;
default: RDCERR("Unrecognised RTV Dimension %d", el.ViewDimension); break;
}
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_RENDER_TARGET_VIEW_DESC1 &el)
{
SERIALISE_MEMBER(Format);
SERIALISE_MEMBER(ViewDimension);
switch(el.ViewDimension)
{
case D3D11_RTV_DIMENSION_UNKNOWN: break;
case D3D11_RTV_DIMENSION_BUFFER: SERIALISE_MEMBER(Buffer); break;
case D3D11_RTV_DIMENSION_TEXTURE1D: SERIALISE_MEMBER(Texture1D); break;
case D3D11_RTV_DIMENSION_TEXTURE1DARRAY: SERIALISE_MEMBER(Texture1DArray); break;
case D3D11_RTV_DIMENSION_TEXTURE2D: SERIALISE_MEMBER(Texture2D); break;
case D3D11_RTV_DIMENSION_TEXTURE2DARRAY: SERIALISE_MEMBER(Texture2DArray); break;
case D3D11_RTV_DIMENSION_TEXTURE2DMS: SERIALISE_MEMBER(Texture2DMS); break;
case D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY: SERIALISE_MEMBER(Texture2DMSArray); break;
case D3D11_RTV_DIMENSION_TEXTURE3D: SERIALISE_MEMBER(Texture3D); break;
default: RDCERR("Unrecognised RTV Dimension %d", el.ViewDimension); break;
}
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_BUFFER_UAV &el)
{
SERIALISE_MEMBER(FirstElement);
SERIALISE_MEMBER(NumElements);
SERIALISE_MEMBER_TYPED(D3D11_BUFFER_UAV_FLAG, Flags);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX1D_UAV &el)
{
SERIALISE_MEMBER(MipSlice);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX1D_ARRAY_UAV &el)
{
SERIALISE_MEMBER(MipSlice);
SERIALISE_MEMBER(FirstArraySlice);
SERIALISE_MEMBER(ArraySize);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2D_UAV &el)
{
SERIALISE_MEMBER(MipSlice);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2D_ARRAY_UAV &el)
{
SERIALISE_MEMBER(MipSlice);
SERIALISE_MEMBER(FirstArraySlice);
SERIALISE_MEMBER(ArraySize);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2D_UAV1 &el)
{
SERIALISE_MEMBER(MipSlice);
SERIALISE_MEMBER(PlaneSlice);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2D_ARRAY_UAV1 &el)
{
SERIALISE_MEMBER(MipSlice);
SERIALISE_MEMBER(FirstArraySlice);
SERIALISE_MEMBER(ArraySize);
SERIALISE_MEMBER(PlaneSlice);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX3D_UAV &el)
{
SERIALISE_MEMBER(MipSlice);
SERIALISE_MEMBER(FirstWSlice);
SERIALISE_MEMBER(WSize);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_UNORDERED_ACCESS_VIEW_DESC &el)
{
SERIALISE_MEMBER(Format);
SERIALISE_MEMBER(ViewDimension);
switch(el.ViewDimension)
{
case D3D11_UAV_DIMENSION_UNKNOWN: break;
case D3D11_UAV_DIMENSION_BUFFER: SERIALISE_MEMBER(Buffer); break;
case D3D11_UAV_DIMENSION_TEXTURE1D: SERIALISE_MEMBER(Texture1D); break;
case D3D11_UAV_DIMENSION_TEXTURE1DARRAY: SERIALISE_MEMBER(Texture1DArray); break;
case D3D11_UAV_DIMENSION_TEXTURE2D: SERIALISE_MEMBER(Texture2D); break;
case D3D11_UAV_DIMENSION_TEXTURE2DARRAY: SERIALISE_MEMBER(Texture2DArray); break;
case D3D11_UAV_DIMENSION_TEXTURE3D: SERIALISE_MEMBER(Texture3D); break;
default: RDCERR("Unrecognised RTV Dimension %d", el.ViewDimension); break;
}
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_UNORDERED_ACCESS_VIEW_DESC1 &el)
{
SERIALISE_MEMBER(Format);
SERIALISE_MEMBER(ViewDimension);
switch(el.ViewDimension)
{
case D3D11_UAV_DIMENSION_UNKNOWN: break;
case D3D11_UAV_DIMENSION_BUFFER: SERIALISE_MEMBER(Buffer); break;
case D3D11_UAV_DIMENSION_TEXTURE1D: SERIALISE_MEMBER(Texture1D); break;
case D3D11_UAV_DIMENSION_TEXTURE1DARRAY: SERIALISE_MEMBER(Texture1DArray); break;
case D3D11_UAV_DIMENSION_TEXTURE2D: SERIALISE_MEMBER(Texture2D); break;
case D3D11_UAV_DIMENSION_TEXTURE2DARRAY: SERIALISE_MEMBER(Texture2DArray); break;
case D3D11_UAV_DIMENSION_TEXTURE3D: SERIALISE_MEMBER(Texture3D); break;
default: RDCERR("Unrecognised UAV Dimension %d", el.ViewDimension); break;
}
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX1D_DSV &el)
{
SERIALISE_MEMBER(MipSlice);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX1D_ARRAY_DSV &el)
{
SERIALISE_MEMBER(MipSlice);
SERIALISE_MEMBER(FirstArraySlice);
SERIALISE_MEMBER(ArraySize);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2D_DSV &el)
{
SERIALISE_MEMBER(MipSlice);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2D_ARRAY_DSV &el)
{
SERIALISE_MEMBER(MipSlice);
SERIALISE_MEMBER(FirstArraySlice);
SERIALISE_MEMBER(ArraySize);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2DMS_DSV &el)
{
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_TEX2DMS_ARRAY_DSV &el)
{
SERIALISE_MEMBER(FirstArraySlice);
SERIALISE_MEMBER(ArraySize);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_DEPTH_STENCIL_VIEW_DESC &el)
{
SERIALISE_MEMBER(Format);
SERIALISE_MEMBER(ViewDimension);
SERIALISE_MEMBER_TYPED(D3D11_DSV_FLAG, Flags);
switch(el.ViewDimension)
{
case D3D11_DSV_DIMENSION_UNKNOWN: break;
case D3D11_DSV_DIMENSION_TEXTURE1D: SERIALISE_MEMBER(Texture1D); break;
case D3D11_DSV_DIMENSION_TEXTURE1DARRAY: SERIALISE_MEMBER(Texture1DArray); break;
case D3D11_DSV_DIMENSION_TEXTURE2D: SERIALISE_MEMBER(Texture2D); break;
case D3D11_DSV_DIMENSION_TEXTURE2DARRAY: SERIALISE_MEMBER(Texture2DArray); break;
case D3D11_DSV_DIMENSION_TEXTURE2DMS: SERIALISE_MEMBER(Texture2DMS); break;
case D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY: SERIALISE_MEMBER(Texture2DMSArray); break;
default: RDCERR("Unrecognised DSV Dimension %d", el.ViewDimension); break;
}
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_RENDER_TARGET_BLEND_DESC &el)
{
SERIALISE_MEMBER_TYPED(bool, BlendEnable);
SERIALISE_MEMBER(SrcBlend);
SERIALISE_MEMBER(DestBlend);
SERIALISE_MEMBER(BlendOp);
SERIALISE_MEMBER(SrcBlendAlpha);
SERIALISE_MEMBER(DestBlendAlpha);
SERIALISE_MEMBER(BlendOpAlpha);
SERIALISE_MEMBER_TYPED(D3D11_COLOR_WRITE_ENABLE, RenderTargetWriteMask);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_RENDER_TARGET_BLEND_DESC1 &el)
{
SERIALISE_MEMBER_TYPED(bool, BlendEnable);
SERIALISE_MEMBER_TYPED(bool, LogicOpEnable);
SERIALISE_MEMBER(SrcBlend);
SERIALISE_MEMBER(DestBlend);
SERIALISE_MEMBER(BlendOp);
SERIALISE_MEMBER(SrcBlendAlpha);
SERIALISE_MEMBER(DestBlendAlpha);
SERIALISE_MEMBER(BlendOpAlpha);
SERIALISE_MEMBER(LogicOp);
SERIALISE_MEMBER_TYPED(D3D11_COLOR_WRITE_ENABLE, RenderTargetWriteMask);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_BLEND_DESC &el)
{
SERIALISE_MEMBER_TYPED(bool, AlphaToCoverageEnable);
SERIALISE_MEMBER_TYPED(bool, IndependentBlendEnable);
SERIALISE_MEMBER(RenderTarget);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_BLEND_DESC1 &el)
{
SERIALISE_MEMBER_TYPED(bool, AlphaToCoverageEnable);
SERIALISE_MEMBER_TYPED(bool, IndependentBlendEnable);
SERIALISE_MEMBER(RenderTarget);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_DEPTH_STENCILOP_DESC &el)
{
SERIALISE_MEMBER(StencilFailOp);
SERIALISE_MEMBER(StencilDepthFailOp);
SERIALISE_MEMBER(StencilPassOp);
SERIALISE_MEMBER(StencilFunc);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_DEPTH_STENCIL_DESC &el)
{
SERIALISE_MEMBER_TYPED(bool, DepthEnable);
SERIALISE_MEMBER(DepthWriteMask);
SERIALISE_MEMBER(DepthFunc);
SERIALISE_MEMBER_TYPED(bool, StencilEnable);
SERIALISE_MEMBER(StencilReadMask);
SERIALISE_MEMBER(StencilWriteMask);
SERIALISE_MEMBER(FrontFace);
SERIALISE_MEMBER(BackFace);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_RASTERIZER_DESC &el)
{
SERIALISE_MEMBER(FillMode);
SERIALISE_MEMBER(CullMode);
SERIALISE_MEMBER_TYPED(bool, FrontCounterClockwise);
SERIALISE_MEMBER(DepthBias);
SERIALISE_MEMBER(DepthBiasClamp);
SERIALISE_MEMBER(SlopeScaledDepthBias);
SERIALISE_MEMBER_TYPED(bool, DepthClipEnable);
SERIALISE_MEMBER_TYPED(bool, ScissorEnable);
SERIALISE_MEMBER_TYPED(bool, MultisampleEnable);
SERIALISE_MEMBER_TYPED(bool, AntialiasedLineEnable);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_RASTERIZER_DESC1 &el)
{
SERIALISE_MEMBER(FillMode);
SERIALISE_MEMBER(CullMode);
SERIALISE_MEMBER_TYPED(bool, FrontCounterClockwise);
SERIALISE_MEMBER(DepthBias);
SERIALISE_MEMBER(DepthBiasClamp);
SERIALISE_MEMBER(SlopeScaledDepthBias);
SERIALISE_MEMBER_TYPED(bool, DepthClipEnable);
SERIALISE_MEMBER_TYPED(bool, ScissorEnable);
SERIALISE_MEMBER_TYPED(bool, MultisampleEnable);
SERIALISE_MEMBER_TYPED(bool, AntialiasedLineEnable);
SERIALISE_MEMBER(ForcedSampleCount);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_RASTERIZER_DESC2 &el)
{
SERIALISE_MEMBER(FillMode);
SERIALISE_MEMBER(CullMode);
SERIALISE_MEMBER_TYPED(bool, FrontCounterClockwise);
SERIALISE_MEMBER(DepthBias);
SERIALISE_MEMBER(DepthBiasClamp);
SERIALISE_MEMBER(SlopeScaledDepthBias);
SERIALISE_MEMBER_TYPED(bool, DepthClipEnable);
SERIALISE_MEMBER_TYPED(bool, ScissorEnable);
SERIALISE_MEMBER_TYPED(bool, MultisampleEnable);
SERIALISE_MEMBER_TYPED(bool, AntialiasedLineEnable);
SERIALISE_MEMBER(ForcedSampleCount);
SERIALISE_MEMBER(ConservativeRaster);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_QUERY_DESC &el)
{
SERIALISE_MEMBER(Query);
SERIALISE_MEMBER(MiscFlags);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_QUERY_DESC1 &el)
{
SERIALISE_MEMBER(Query);
SERIALISE_MEMBER(MiscFlags);
SERIALISE_MEMBER(ContextType);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_COUNTER_DESC &el)
{
SERIALISE_MEMBER(Counter);
SERIALISE_MEMBER(MiscFlags);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_SAMPLER_DESC &el)
{
SERIALISE_MEMBER(Filter);
SERIALISE_MEMBER(AddressU);
SERIALISE_MEMBER(AddressV);
SERIALISE_MEMBER(AddressW);
SERIALISE_MEMBER(MipLODBias);
SERIALISE_MEMBER(MaxAnisotropy);
SERIALISE_MEMBER(ComparisonFunc);
SERIALISE_MEMBER(BorderColor);
SERIALISE_MEMBER(MinLOD);
SERIALISE_MEMBER(MaxLOD);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_SO_DECLARATION_ENTRY &el)
{
SERIALISE_MEMBER(Stream);
SERIALISE_MEMBER(SemanticName);
SERIALISE_MEMBER(SemanticIndex);
SERIALISE_MEMBER(StartComponent);
SERIALISE_MEMBER(ComponentCount);
SERIALISE_MEMBER(OutputSlot);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_INPUT_ELEMENT_DESC &el)
{
SERIALISE_MEMBER(SemanticName);
SERIALISE_MEMBER(SemanticIndex);
SERIALISE_MEMBER(Format);
SERIALISE_MEMBER(InputSlot);
SERIALISE_MEMBER(AlignedByteOffset);
SERIALISE_MEMBER(InputSlotClass);
SERIALISE_MEMBER(InstanceDataStepRate);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_SUBRESOURCE_DATA &el)
{
// don't serialise pSysMem, just set it to NULL. See the definition of SERIALISE_MEMBER_DUMMY
SERIALISE_MEMBER_ARRAY_EMPTY(pSysMem);
SERIALISE_MEMBER(SysMemPitch);
SERIALISE_MEMBER(SysMemSlicePitch);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_VIEWPORT &el)
{
SERIALISE_MEMBER(TopLeftX);
SERIALISE_MEMBER(TopLeftY);
SERIALISE_MEMBER(Width);
SERIALISE_MEMBER(Height);
SERIALISE_MEMBER(MinDepth);
SERIALISE_MEMBER(MaxDepth);
}
template <class SerialiserType>
void DoSerialise(SerialiserType &ser, D3D11_BOX &el)
{
SERIALISE_MEMBER(left);
SERIALISE_MEMBER(top);
SERIALISE_MEMBER(front);
SERIALISE_MEMBER(right);
SERIALISE_MEMBER(bottom);
SERIALISE_MEMBER(back);
}
INSTANTIATE_SERIALISE_TYPE(D3D11_BUFFER_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEXTURE1D_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEXTURE2D_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEXTURE2D_DESC1);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEXTURE3D_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEXTURE3D_DESC1);
INSTANTIATE_SERIALISE_TYPE(D3D11_BUFFER_SRV);
INSTANTIATE_SERIALISE_TYPE(D3D11_BUFFEREX_SRV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX1D_SRV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX1D_ARRAY_SRV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2D_SRV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2D_ARRAY_SRV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2D_SRV1);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2D_ARRAY_SRV1);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX3D_SRV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEXCUBE_SRV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEXCUBE_ARRAY_SRV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2DMS_SRV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2DMS_ARRAY_SRV);
INSTANTIATE_SERIALISE_TYPE(D3D11_SHADER_RESOURCE_VIEW_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_SHADER_RESOURCE_VIEW_DESC1);
INSTANTIATE_SERIALISE_TYPE(D3D11_BUFFER_RTV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX1D_RTV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX1D_ARRAY_RTV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2D_RTV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2D_ARRAY_RTV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2DMS_RTV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2DMS_ARRAY_RTV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2D_RTV1);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2D_ARRAY_RTV1);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX3D_RTV);
INSTANTIATE_SERIALISE_TYPE(D3D11_RENDER_TARGET_VIEW_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_RENDER_TARGET_VIEW_DESC1);
INSTANTIATE_SERIALISE_TYPE(D3D11_BUFFER_UAV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX1D_UAV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX1D_ARRAY_UAV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2D_UAV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2D_ARRAY_UAV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2D_UAV1);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2D_ARRAY_UAV1);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX3D_UAV);
INSTANTIATE_SERIALISE_TYPE(D3D11_UNORDERED_ACCESS_VIEW_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_UNORDERED_ACCESS_VIEW_DESC1);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX1D_DSV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX1D_ARRAY_DSV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2D_DSV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2D_ARRAY_DSV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2DMS_DSV);
INSTANTIATE_SERIALISE_TYPE(D3D11_TEX2DMS_ARRAY_DSV);
INSTANTIATE_SERIALISE_TYPE(D3D11_DEPTH_STENCIL_VIEW_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_RENDER_TARGET_BLEND_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_RENDER_TARGET_BLEND_DESC1);
INSTANTIATE_SERIALISE_TYPE(D3D11_BLEND_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_BLEND_DESC1);
INSTANTIATE_SERIALISE_TYPE(D3D11_DEPTH_STENCILOP_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_DEPTH_STENCIL_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_RASTERIZER_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_RASTERIZER_DESC1);
INSTANTIATE_SERIALISE_TYPE(D3D11_RASTERIZER_DESC2);
INSTANTIATE_SERIALISE_TYPE(D3D11_QUERY_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_QUERY_DESC1);
INSTANTIATE_SERIALISE_TYPE(D3D11_COUNTER_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_SAMPLER_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_SO_DECLARATION_ENTRY);
INSTANTIATE_SERIALISE_TYPE(D3D11_INPUT_ELEMENT_DESC);
INSTANTIATE_SERIALISE_TYPE(D3D11_SUBRESOURCE_DATA);
INSTANTIATE_SERIALISE_TYPE(D3D11_VIEWPORT);
INSTANTIATE_SERIALISE_TYPE(D3D11_RECT);
INSTANTIATE_SERIALISE_TYPE(D3D11_BOX);
| [
"baldurk@baldurk.org"
] | baldurk@baldurk.org |
f8367340490469b3fec83e0e2bc814a39e9a16ec | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/multimedia/directx/dmusic/dmscript/englog.cpp | 86fe8cdb493fb7529d453448b600154f3ab6e3fe | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 8,267 | cpp | // Copyright (c) 1999 Microsoft Corporation. All rights reserved.
//
// Helper functions for logging script parsing. Useful for debugging, but never turned on in released builds.
//
#error This file should never be used in released builds. // §§
#include "stdinc.h"
#include "englog.h"
void LogToken(Lexer &l)
{
char msg[500] = "";
char type[500] = "";
char more[500] = "";
switch (l)
{
case TOKEN_eof:
if (l.error_num())
{
sprintf(msg, "%d(%d): error #%d - %s\n", l.line(), l.column(), l.error_num(), l.error_descr());
OutputDebugString(msg);
return;
}
strcpy(type, "end-of-file");
break;
case TOKEN_sub:
strcpy(type, "sub");
break;
case TOKEN_dim:
strcpy(type, "dim");
break;
case TOKEN_if:
strcpy(type, "if");
break;
case TOKEN_then:
strcpy(type, "then");
break;
case TOKEN_end:
strcpy(type, "end");
break;
case TOKEN_elseif:
strcpy(type, "elseif");
break;
case TOKEN_else:
strcpy(type, "else");
break;
case TOKEN_set:
strcpy(type, "set");
break;
case TOKEN_call:
strcpy(type, "call");
break;
case TOKEN_lparen:
strcpy(type, "(");
break;
case TOKEN_rparen:
strcpy(type, ")");
break;
case TOKEN_comma:
strcpy(type, ",");
break;
case TOKEN_op_minus:
strcpy(type, "-");
break;
case TOKEN_op_not:
strcpy(type, "not");
break;
case TOKEN_op_pow:
strcpy(type, "^");
break;
case TOKEN_op_mult:
strcpy(type, "*");
break;
case TOKEN_op_div:
strcpy(type, "\\");
break;
case TOKEN_op_mod:
strcpy(type, "mod");
break;
case TOKEN_op_plus:
strcpy(type, "+");
break;
case TOKEN_op_lt:
strcpy(type, "<");
break;
case TOKEN_op_leq:
strcpy(type, "<=");
break;
case TOKEN_op_gt:
strcpy(type, ">");
break;
case TOKEN_op_geq:
strcpy(type, ">=");
break;
case TOKEN_op_eq:
strcpy(type, "=");
break;
case TOKEN_op_neq:
strcpy(type, "<>");
break;
case TOKEN_is:
strcpy(type, "is");
break;
case TOKEN_and:
strcpy(type, "and");
break;
case TOKEN_or:
strcpy(type, "or");
break;
case TOKEN_linebreak:
strcpy(type, "linebreak");
break;
case TOKEN_identifier:
strcpy(type, "identifier");
strcpy(more, l.identifier_name());
break;
case TOKEN_identifierdot:
strcpy(type, "identifier.");
strcpy(more, l.identifier_name());
break;
case TOKEN_stringliteral:
strcpy(type, "string-literal");
strcpy(more, l.stringliteral_text());
break;
case TOKEN_numericliteral:
strcpy(type, "numeric-literal");
_itoa(l.numericliteral_val(), more, 10);
break;
default:
strcpy(type, "invalid token type!");
break;
}
static const char format[] = "%d(%d): %s\n";
static const char formatmore[] = "%d(%d): %s(%s)\n";
sprintf(msg, *more ? formatmore : format, l.line(), l.column(), type, more);
OutputDebugString(msg);
}
SmartRef::AString GetVarrefName(Script &script, VariableReferences::index ivarref)
{
VariableReference r = script.varrefs[ivarref];
const char *pszKind;
if (r.k == VariableReference::_global)
pszKind = "G";
else if (r.k == VariableReference::_local)
pszKind = "L";
bool fFirst = true;
char namebuf[500] = "";
for (ReferenceNames::index irname = r.irname; script.rnames[irname].istrIdentifier != -1; ++irname)
{
if (fFirst)
fFirst = false;
else
strcat(namebuf, ".");
strcat(namebuf, script.strings[script.rnames[irname].istrIdentifier]);
}
Variables::index islot = r.ivar;
// check if it's a dispatch item
if (r.k == VariableReference::_global)
{
DISPID dispid = script.globals[islot].dispid;
if (dispid != DISPID_UNKNOWN)
{
pszKind = "D";
islot = dispid; // show the dispid instead of the slot
}
}
char buf[500];
sprintf(buf, "{%s%d}%s", pszKind, islot, namebuf);
return buf;
}
SmartRef::AString GetValueName(Script &script, Values::index ival)
{
const Value &v = script.vals[ival];
char buf[500];
if (v.k == Value::_numvalue)
{
sprintf(buf, "%d", v.inumvalue);
}
else if (v.k == Value::_strvalue)
{
sprintf(buf, "\"%s\"", script.strings[v.istrvalue]);
}
else
{
assert(v.k == Value::_varref);
return GetVarrefName(script, v.ivarref);
}
return buf;
}
void Indent(int iNesting)
{
for (int i = 0; i < iNesting; ++i)
OutputDebugString(" ");
}
// forward declaration due to mutual recursion with LogExpression
void LogCall(Script &script, Calls::index icall);
ExprBlocks::index LogExpression(Script &script, ExprBlocks::index _iexpr)
{
char msg[500] = "";
bool fFirst = true;
for (ExprBlocks::index iexpr = _iexpr; script.exprs[iexpr]; ++iexpr)
{
ExprBlock expr = script.exprs[iexpr];
if (fFirst)
fFirst = false;
else
OutputDebugString("|");
if (expr.k == ExprBlock::_op)
{
bool fUnary = false;
const char *pszOp = "";
switch (expr.op)
{
case TOKEN_sub: fUnary = true; pszOp = "-"; break;
case TOKEN_op_not: fUnary = true; pszOp = "not"; break;
case TOKEN_op_minus: pszOp = "-"; break;
case TOKEN_op_pow: pszOp = "^"; break;
case TOKEN_op_mult: pszOp = "*"; break;
case TOKEN_op_div: pszOp = "\\"; break;
case TOKEN_op_mod: pszOp = "mod"; break;
case TOKEN_op_plus: pszOp = "+"; break;
case TOKEN_op_lt: pszOp = "<"; break;
case TOKEN_op_leq: pszOp = "<="; break;
case TOKEN_op_gt: pszOp = ">"; break;
case TOKEN_op_geq: pszOp = ">="; break;
case TOKEN_op_eq: pszOp = "="; break;
case TOKEN_op_neq: pszOp = "<>"; break;
case TOKEN_is: pszOp = "is"; break;
case TOKEN_and: pszOp = "and"; break;
case TOKEN_or: pszOp = "or"; break;
default: assert(false); break;
}
if (fUnary)
sprintf(msg, "%su", pszOp);
else
sprintf(msg, "%sb", pszOp);
OutputDebugString(msg);
}
else if (expr.k == ExprBlock::_val)
{
SmartRef::AString astrVal = GetValueName(script, expr.ival);
OutputDebugString(astrVal);
}
else
{
assert(expr.k == ExprBlock::_call);
LogCall(script, expr.icall);
}
}
return iexpr;
}
void LogCall(Script &script, Calls::index icall)
{
Call c = script.calls[icall];
if (c.k == Call::_global)
{
OutputDebugString(script.strings[c.istrname]);
}
else
{
assert(c.k == Call::_dereferenced);
SmartRef::AString astrCall = GetVarrefName(script, c.ivarref);
OutputDebugString(astrCall);
}
OutputDebugString("(");
bool fFirst = true;
for (ExprBlocks::index iexpr = c.iexprParams; script.exprs[iexpr]; ++iexpr)
{
if (fFirst)
fFirst = false;
else
OutputDebugString(", ");
iexpr = LogExpression(script, iexpr);
}
OutputDebugString(")");
}
void LogStatements(Script &script, Statements::index istmt, int iNesting)
{
char msg[500] = "";
for (; script.statements[istmt].k; ++istmt)
{
Statement s = script.statements[istmt];
if (s.k == Statement::_asgn)
{
Assignment a = script.asgns[s.iasgn];
SmartRef::AString astrLHS = GetVarrefName(script, a.ivarrefLHS);
sprintf(msg, "%s = ", astrLHS);
Indent(iNesting);
OutputDebugString(msg);
LogExpression(script, a.iexprRHS);
OutputDebugString("\n");
}
else if (s.k == Statement::_if)
{
bool fFirst = true;
for (IfBlocks::index iif = s.iif; script.ifs[iif].k != IfBlock::_end; ++iif)
{
Indent(iNesting);
IfBlock ib = script.ifs[iif];
if (fFirst)
{
assert(ib.k == IfBlock::_cond);
OutputDebugString("if ");
fFirst = false;
}
else
{
if (ib.k == IfBlock::_cond)
OutputDebugString("elseif ");
else if (ib.k == IfBlock::_else)
OutputDebugString("else");
}
if (ib.k == IfBlock::_cond)
{
LogExpression(script, ib.iexprCondition);
}
OutputDebugString("\n");
LogStatements(script, ib.istmtBlock, iNesting + 3);
}
istmt = s.istmtIfTail - 1; // -1 to offset the loop, which will increment it back
}
else if (s.k == Statement::_call)
{
Indent(iNesting);
LogCall(script, s.icall);
OutputDebugString("\n");
}
else
{
assert(false);
Indent(iNesting);
OutputDebugString(" Unknown statement type!\n");
}
}
}
void LogRoutine(Script &script, Routines::index irtn)
{
Routine r = script.routines[irtn];
const char *pszName = script.strings[r.istrIdentifier];
int cLocals = r.ivarNextLocal;
char msg[500] = "";
sprintf(msg, "@ Sub %s (%d locals)\n", pszName, cLocals);
OutputDebugString(msg);
LogStatements(script, r.istmtBody, 3);
}
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
868e9dfd97439641e1c4adc679cd2abc8f3d589f | 7f2743effa89a8a36f3b30a7df8e3cec061a2202 | /comlineargs.cc | 849517e413f110a75cf51517020a2126871c50a7 | [] | no_license | allisonchanykei/SchoolCplusplus | 2745972ed33ea995651fa357919fadb5b69be758 | 2c88d5334891692d8f3b7f1715706161716664b1 | refs/heads/master | 2021-01-13T10:21:07.566840 | 2016-09-24T20:56:18 | 2016-09-24T20:56:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 155 | cc | #include <iostream>
using namespace std;
int main (int argc, char* argv[]){
for (int x=0;x<argc;x++){
cout<<argv[x]<<" ";
}
cout<<endl;
return 0;
}
| [
"allisonchanykei@gmail.com"
] | allisonchanykei@gmail.com |
fd43d95c13430163e9683b7845642c337475b0fe | 1d7baf8f25e3cdc2c028f0642a38fb3303a1f831 | /src/param/bean/param.hpp | 5488769dab388ccb61472c836f78cdf672d3ac0f | [] | no_license | fightinggg/pocker | e0cbfd19b47d982c2aa2f50116744573e8119b75 | dd40f8b51ebd3e5f380a67168eaa06c4753119b0 | refs/heads/master | 2023-05-15T03:35:47.037576 | 2021-06-05T03:11:10 | 2021-06-05T03:11:10 | 359,097,772 | 10 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 87 | hpp | #pragma once
#include "./param_type.hpp"
class param {
public:
param_type type;
}; | [
"246553278@qq.com"
] | 246553278@qq.com |
de1f95c0528852dfa0e8eca5c9e1627785902e71 | 55cebabd188a4c2053c1cc8134f0f46b158e7c26 | /src/algorithm/AASqlStructs.cpp | aab53dc62e100f96a873bc0a80e5b0d7cb82fd07 | [
"BSD-3-Clause"
] | permissive | Army-Ant/ArmyAntLib_Old | 8755d41e76058e1769403402dcb171a80252ffbe | f00dc2227870c1bfa7806a91db336300195dabf4 | refs/heads/master | 2021-09-22T22:46:24.102310 | 2018-09-18T10:47:37 | 2018-09-18T10:47:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,046 | cpp | /* Copyright (c) 2015 ArmyAnt
* 版权所有 (c) 2015 ArmyAnt
*
* Licensed under the BSD License, Version 2.0 (the License);
* 本软件使用BSD协议保护, 协议版本:2.0
* you may not use this file except in compliance with the License.
* 使用本开源代码文件的内容, 视为同意协议
* You can read the license content in the file "LICENSE" at the root of this project
* 您可以在本项目的根目录找到名为"LICENSE"的文件, 来阅读协议内容
* You may also obtain a copy of the License at
* 您也可以在此处获得协议的副本:
*
* http://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* 除非法律要求或者版权所有者书面同意,本软件在本协议基础上的发布没有任何形式的条件和担保,无论明示的或默许的.
* See the License for the specific language governing permissions and limitations under the License.
* 请在特定限制或语言管理权限下阅读协议
* This file is the internal source file of this project, is not contained by the closed source release part of this software
* 本文件为内部源码文件, 不会包含在闭源发布的本软件中
*/
#include <vector>
#include "../../inc/AASqlStructs.h"
#include "../../inc/AAClassPrivateHandle.hpp"
#define AA_SQL_EXPRESS_HANDLE_MANAGER ClassPrivateHandleManager<SqlExpress, SqlExpress_inner>::getInstance()
#define AA_SQL_CLAUSE_HANDLE_MANAGER ClassPrivateHandleManager<SqlClause, SqlClause_inner>::getInstance()
namespace ArmyAnt
{
String SqlStructHelper::getDataTypeName(SqlFieldType type) {
switch (type) {
case SqlFieldType::Null:
return "null";
case SqlFieldType::MySql_BIT:
return "bit";
case SqlFieldType::MySql_CHAR: // TODO: mysql所有项目以及部分SqlServer项目都应当对括号内的长度限制作处理
return "char(255)";
case SqlFieldType::MySql_VARCHAR: //
return "varchar(1024)";
case SqlFieldType::MySql_GEOMETRY:
return "geometry";
case SqlFieldType::MsSqlServer_text:
return "text";
case SqlFieldType::MySql_BINARY: //
return "binary(4096)";
case SqlFieldType::MySql_VARBINARY: //
return "varbinary(32768)";
case SqlFieldType::MySql_LONGVARCHAR: //
return "varchar(32768)";
case SqlFieldType::MySql_LONGVARBINARY: //
return "varbinary(262144)";
case SqlFieldType::MySql_JSON:
return "json";
case SqlFieldType::MySql_ENUM:
return "enum()"; // TODO: 需要对mysql枚举作特殊处理,下面set同
case SqlFieldType::MySql_SET:
return "set";
case SqlFieldType::MySql_TINYINT:
return "tinyint";
case SqlFieldType::MySql_SMALLINT:
return "smallint";
case SqlFieldType::MySql_MEDIUMINT:
return "mediumint";
case SqlFieldType::MySql_INT:
return "int";
case SqlFieldType::MySql_BIGINT:
return "bigint";
case SqlFieldType::MySql_FLOAT:
return "float";
case SqlFieldType::MySql_DOUBLE:
return "double";
case SqlFieldType::MySql_DEMICAL:
return "demical";
case SqlFieldType::MySql_DATE:
case SqlFieldType::MsSqlServer_date:
return "date";
case SqlFieldType::MySql_DATETIME:
case SqlFieldType::MsSqlServer_datetime:
return "datetime";
case SqlFieldType::MySql_TIMESTAMP:
case SqlFieldType::MsSqlServer_timestamp:
return "timestamp";
case SqlFieldType::MySql_TIME:
case SqlFieldType::MsSqlServer_time:
return "time";
case SqlFieldType::MySql_YEAR:
return "year";
case SqlFieldType::MsAccess_Currency:
return "Currency";
case SqlFieldType::MsAccess_AutoNumber:
return "AutoNumber";
case SqlFieldType::MsAccess_YesNo:
return "Yes/No";
case SqlFieldType::MsAccess_Hyperlink:
return "Hyperlink";
case SqlFieldType::MsAccess_Text:// = MySql_Varchar,
return "Text";
case SqlFieldType::MsAccess_Memo:// = MySql_Text,
return "Memo";
case SqlFieldType::MsAccess_Byte:// = MySql_TinyInt,
return "Byte";
case SqlFieldType::MsAccess_Integer:// = MySql_SmallInt,
return "Integer";
case SqlFieldType::MsAccess_Long:// = MySql_Int,
return "Long";
case SqlFieldType::MsAccess_Single:// = MySql_Float,
return "Single";
case SqlFieldType::MsAccess_Double:// = MySql_Double,
return "Double";
case SqlFieldType::MsAccess_DateTime:// = MySql_DateTime,
return "Date/Time";
case SqlFieldType::MsAccess_OleObject:// = MySql_LongBlob,
return "Ole Object";
case SqlFieldType::MsAccess_LookupWizard:// = MySql_Enum,
return "Lookup Wizard";
case SqlFieldType::MsSqlServer_char:
return "char(8000)";
case SqlFieldType::MsSqlServer_varchar:
return "varchar(max)";
case SqlFieldType::MsSqlServer_nchar:
return "nchar(4000)";
case SqlFieldType::MsSqlServer_nvarchar:
return "nvarchar(4000)";
case SqlFieldType::MsSqlServer_ntext:
return "ntext";
case SqlFieldType::MsSqlServer_bit:
return "bit";
case SqlFieldType::MsSqlServer_binary:
return "binary(8000)";
case SqlFieldType::MsSqlServer_varbinary:
return "varbinary(max)";
case SqlFieldType::MsSqlServer_image:
return "image";
case SqlFieldType::MsSqlServer_tinyint:
return "tinyint";
case SqlFieldType::MsSqlServer_smallint:
return "smallint";
case SqlFieldType::MsSqlServer_int:
return "int";
case SqlFieldType::MsSqlServer_bigint:
return "bigint";
case SqlFieldType::MsSqlServer_decimal:
return "demical";
case SqlFieldType::MsSqlServer_numeric:
return "numeric";
case SqlFieldType::MsSqlServer_smallmoney:
return "smallmoney";
case SqlFieldType::MsSqlServer_money:
return "money";
case SqlFieldType::MsSqlServer_float:
return "float";
case SqlFieldType::MsSqlServer_real:
return "real";
case SqlFieldType::MsSqlServer_datetime2:
return "datetime2";
case SqlFieldType::MsSqlServer_smalldatetime:
return "smalldatetime";
case SqlFieldType::MsSqlServer_datetimeoffset:
return "datetimeoffset";
case SqlFieldType::MsSqlServer_sql_variant:
return "sql_variant";
case SqlFieldType::MsSqlServer_uniqueidentifier:
return "uniqueidentifier";
case SqlFieldType::MsSqlServer_xml:
return "xml";
case SqlFieldType::MsSqlServer_cursor:
return "cursor";
case SqlFieldType::MsSqlServer_table:
return "table";
case SqlFieldType::MsExcel_Normal:
return "excel";
default:
return "";
}
}
SqlField::SqlField()
:head(nullptr), value("")
{
}
SqlField::SqlField(const String & value, const SqlFieldHead * head)
:head(head), value(value)
{
}
SqlField::~SqlField()
{
}
bool SqlField::setValue(const String & v)
{
value = v;
return true;
}
const String & SqlField::getValue() const
{
return value;
}
const SqlFieldHead * SqlField::getHead() const
{
return head;
}
SqlRow::SqlRow(const SqlRow & copied)
:length(copied.length), fields(nullptr)
{
if (length <= 0)
return;
fields = new SqlField[length];
for (uint32 i = 0; i < length; ++i)
{
fields[i] = copied.fields[i];
}
}
SqlRow::SqlRow(SqlRow && moved)
:length(moved.length), fields(moved.fields)
{
moved.length = 0;
moved.fields = nullptr;
}
SqlRow::~SqlRow()
{
Fragment::AA_SAFE_DELALL(fields);
}
uint32 SqlRow::size() const
{
return length;
}
const SqlField & SqlRow::operator[](int32 index)const
{
return const_cast<SqlRow*>(this)->operator[](index);
}
SqlField & SqlRow::operator[](int32 index){
if(index < 0)
index += length;
if(index >= length || index < 0)
throw nullptr;
return fields[index];
}
SqlColumn::SqlColumn(const SqlColumn & copied)
:fields(nullptr), indexes(nullptr), length(copied.length)
{
if (length <= 0)
return;
fields = new SqlField[length];
indexes = new uint32[length];
for (uint32 i = 0; i < length; ++i)
{
fields[i] = copied.fields[i];
indexes[i] = copied.indexes[i];
}
}
SqlColumn::SqlColumn(SqlColumn && moved)
:fields(moved.fields), indexes(moved.indexes), length(moved.length)
{
moved.fields = nullptr;
moved.length = 0;
moved.indexes = nullptr;
}
SqlColumn::~SqlColumn()
{
Fragment::AA_SAFE_DELALL(indexes);
Fragment::AA_SAFE_DELALL(fields);
}
uint32 SqlColumn::size() const
{
return length;
}
const SqlFieldHead * SqlColumn::getHead(uint32 index) const
{
return operator[](index).getHead();
}
const SqlField & SqlColumn::operator[](int32 index) const
{
return const_cast<SqlColumn*>(this)->operator[](index);
}
SqlField & SqlColumn::operator[](int32 index){
if(index < 0)
index += length;
if(index >= length || index < 0)
throw nullptr;
return fields[index];
}
SqlTable::SqlTable(const SqlTable & copied)
:_width(copied._width), _height(copied._height), heads(nullptr), fields(nullptr)
{
if (_width > 0)
{
heads = new SqlFieldHead[_width];
for (uint32 i = 0; i < _width; ++i)
{
heads[i] = copied.heads[i];
}
if (_height > 0)
{
fields = new SqlField*[_height];
for (uint32 i = 0; i < _height; ++i)
{
fields[i] = new SqlField[_width];
for (uint32 n = 0; n < _width; ++n)
{
fields[i][n] = copied.fields[i][n];
}
}
}
}
}
SqlTable::SqlTable(SqlTable && moved)
:_width(moved._width), _height(moved._height), heads(moved.heads), fields(moved.fields)
{
moved.heads = nullptr;
moved.fields = nullptr;
moved._width = 0;
moved._height = 0;
}
SqlTable & SqlTable::operator=(const SqlTable & copied){
Fragment::AA_SAFE_DELALL(heads);
for(uint32 i = 0; i < _height; ++i){
Fragment::AA_SAFE_DELALL(fields[i]);
}
Fragment::AA_SAFE_DELALL(fields);
_width = copied._width;
_height = copied._height;
if(_width > 0){
heads = new SqlFieldHead[_width];
for(uint32 i = 0; i < _width; ++i){
heads[i] = copied.heads[i];
}
if(_height > 0){
fields = new SqlField*[_height];
for(uint32 i = 0; i < _height; ++i){
fields[i] = new SqlField[_width];
for(uint32 n = 0; n < _width; ++n){
fields[i][n] = copied.fields[i][n];
}
}
}
}
return *this;
}
SqlTable & SqlTable::operator=(SqlTable && moved){
_width = moved._width;
_height = moved._height;
heads = moved.heads;
fields = moved.fields;
moved._width = 0;
moved._height = 0;
moved.heads = nullptr;
moved.fields = nullptr;
return *this;
}
SqlTable::~SqlTable()
{
Fragment::AA_SAFE_DELALL(heads);
for (uint32 i = 0; i < _height; ++i)
{
Fragment::AA_SAFE_DELALL(fields[i]);
}
Fragment::AA_SAFE_DELALL(fields);
}
uint32 SqlTable::size() const
{
return _width*_height;
}
uint32 SqlTable::width() const
{
return _width;
}
uint32 SqlTable::height() const
{
return _height;
}
const SqlFieldHead * SqlTable::getHead(int32 index) const
{
if (index < 0)
index += _width;
if (index >= _width || index < 0)
throw nullptr;
return heads + index;
}
SqlRow SqlTable::operator[](int32 index){
if(index < 0)
index += _height;
if(index >= _height || index < 0 || _width <= 0)
throw nullptr;
char tmp[sizeof(SqlRow)] = "";
SqlRow ret = *reinterpret_cast<SqlRow*>(tmp);
ret.length = _width;
ret.fields = new SqlField[_width];
for(uint32 i = 0; i < _width; ++i){
ret.fields[i] = fields[index][i];
}
return ret;
}
const SqlField & SqlTable::operator()(int32 rowIndex, int32 colIndex)const{
return const_cast<SqlTable*>(this)->operator()(rowIndex, colIndex);
}
SqlField & SqlTable::operator()(int32 rowIndex, int32 colIndex){
if(rowIndex < 0)
rowIndex += _height;
if(colIndex < 0)
colIndex += _width;
if(rowIndex >= _height || rowIndex < 0 || colIndex >= _width || colIndex < 0)
throw nullptr;
return fields[rowIndex][colIndex];
}
SqlColumn SqlTable::operator()(std::nullptr_t, int32 colIndex)
{
if (colIndex < 0)
colIndex += _width;
if (colIndex >= _width || colIndex < 0 || _height <= 0)
throw nullptr;
char tmp[sizeof(SqlColumn)] = "";
SqlColumn ret = *reinterpret_cast<SqlColumn*>(tmp);
ret.length = _height;
ret.fields = new SqlField[_height];
ret.indexes = new uint32[_height];
for (uint32 i = 0; i < _height; ++i)
{
ret.fields[i] = fields[i][colIndex];
ret.indexes[i] = i;
}
return ret;
}
const SqlColumn SqlTable::operator()(std::nullptr_t, int32 colIndex)const
{
return const_cast<SqlTable *>(this)->operator()(nullptr, colIndex);
}
SqlTable::SqlTable(const SqlFieldHead* heads, uint32 width, uint32 height)
:_width(width), _height(height), heads(nullptr), fields(nullptr){
if(width > 0){
this->heads = new SqlFieldHead[width];
for(uint32 i = 0; i < width; ++i){
this->heads[i] = heads[i];
}
if(_height > 0){
fields = new SqlField*[_height];
for(uint32 i = 0; i < _height; ++i){
fields[i] = new SqlField[width];
for(uint32 n = 0; n < _width; ++n){
fields[i][n].head = heads + n;
fields[i][n].value = "";
}
}
}
}
}
/********************* Sql Express ************************************/
class SqlExpress_inner {
std::vector<String> expresses;
};
SqlExpress::SqlExpress(const String & str)
:type(SqlOperatorType::none)
{
AA_SQL_EXPRESS_HANDLE_MANAGER.GetHandle(this);
AAAssert(pushValue(str), );
}
SqlExpress::~SqlExpress()
{
delete AA_SQL_EXPRESS_HANDLE_MANAGER.ReleaseHandle(this);
}
bool SqlExpress::pushValue(const String & value)
{
// TODO
return false;
}
/********************* Sql Clause *************************************/
class SqlClause_inner {
std::vector<SqlExpress> expresses;
};
SqlClause::SqlClause(const String & str)
:type(SqlClauseType::Null)
{
AA_SQL_CLAUSE_HANDLE_MANAGER.GetHandle(this);
}
SqlClause::~SqlClause()
{
delete AA_SQL_CLAUSE_HANDLE_MANAGER.ReleaseHandle(this);
}
}
#undef AA_SQL_EXPRESS_HANDLE_MANAGER
#undef AA_SQL_CLAUSE_HANDLE_MANAGER
| [
"261343578@qq.com"
] | 261343578@qq.com |
cad84a45c36ed3018d7bdd265d864d385ec5b345 | 6681adf01f381e276ee5a86942e7075ea8891dbb | /Graph/include/Node/RouterNode.h | d61002a9ac567b6212c1a5e70c2453db341fd5c7 | [] | no_license | k-pypin/BandwidthGraph | 7359c9d4b2bec7c913fe330892d3f30bcf521efb | 17810a0f3a6c57e4d5d9b1fd55bd26c2c316e8f9 | refs/heads/master | 2023-02-05T13:42:12.875974 | 2020-12-28T23:34:38 | 2020-12-28T23:34:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 476 | h | //
// Created by Trojan on 07.12.2020.
//
#ifndef BANDWIDTHGRAPH_ROUTERNODE_H
#define BANDWIDTHGRAPH_ROUTERNODE_H
#include "Node/BaseBandwidthNode.h"
class RouterNode : public BaseBandwidthNode
{
public:
RouterNode() = default;
virtual ~RouterNode() {};
explicit RouterNode(const nlohmann::json& j) { BaseBandwidthNode::fromJSON(j); };
NodeType getNodeType() override { return NODETYPE_ROUTER; }
};
#endif //BANDWIDTHGRAPH_ROUTERNODE_H
| [
"kirill_131097@mail.ru"
] | kirill_131097@mail.ru |
398191191b8bbf426f2d5e4ce6f3d7603948f450 | 972b3db50e228c2959dd3edf3c9bae025638d82b | /huffmanelementscount.h | 0fcfb2e4984c1f23f142b4ad2a2c801dcb16602e | [
"MIT"
] | permissive | amirduran/jpeg-encoder-decoder | 294977f02e5f3091f177a074f53039e1c907cc49 | 61b6dee27e64587651063a19b5653729bde0047f | refs/heads/master | 2021-01-22T19:14:09.342614 | 2020-06-16T10:01:10 | 2020-06-16T10:01:10 | 27,594,465 | 16 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 272 | h | #ifndef HUFFMANELEMENTSCOUNT_H
#define HUFFMANELEMENTSCOUNT_H
using namespace std;
#include <vector>
class HuffmanElementsCount
{
public:
int codeLength;
vector<int>elementsCodedWithCodeLengthBits;
HuffmanElementsCount();
};
#endif // HUFFMANELEMENTSCOUNT_H
| [
"amirduran"
] | amirduran |
e5c3355bf90aa0de9323d7d30d09981f143a21c8 | 16bb3fc4c2966939d41a55d37e226cfdc7e4b186 | /src/cTexture.cpp | 0dfd4a18f7a85dfb82ea7b848b154b7dc55a34b9 | [] | no_license | alexgg-developer/3d_vj2014 | f050d47e2705f4998f4c3a72d997898637f63bb6 | eed25756da422a5e4db4c41f38387a2dcd1b6c10 | refs/heads/master | 2021-01-22T00:58:33.284237 | 2014-06-01T23:10:50 | 2014-06-01T23:10:50 | 20,878,843 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,246 | cpp | #include "cTexture.hpp"
#include <iostream>
Texture::Texture(): mTexture(0), mWidth(0), mHeight(0), mTextureSurface(nullptr), mProgramID(0)
{
}
Texture::~Texture()
{}
bool Texture::init()
{
bool success = true;
mProgramID = glCreateProgram();
GLShader defaultVertexShader;
defaultVertexShader.init(GLShader::VERTEX, mProgramID);
success = defaultVertexShader.compile();
mVertexShader.push_back(defaultVertexShader);
GLShader defaultFragmentShader;
defaultFragmentShader.init(GLShader::FRAGMENT, mProgramID);
success = defaultFragmentShader.compile();
mFragmentShader.push_back(defaultFragmentShader);
success = GLShader::linkProgram(mProgramID);
GLfloat vertexData[] =
{
-0.5f, -0.5f,
0.5f, -0.5f,
0.5f, 0.5f,
-0.5f, 0.5f
};
GLuint indexData[] = { 0, 1, 2, 3 };
GLuint vbo = 0;
glGenBuffers( 1, &vbo );
glBindBuffer( GL_ARRAY_BUFFER, vbo );
glBufferData( GL_ARRAY_BUFFER, 2 * 4 * sizeof(GLfloat), vertexData, GL_STATIC_DRAW );
mVBO.push_back(vbo);
GLuint ibo = 0;
glGenBuffers( 1, &ibo );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, ibo );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, 4 * sizeof(GLuint), indexData, GL_STATIC_DRAW );
mIBO.push_back(ibo);
glBindBuffer( GL_ARRAY_BUFFER, NULL ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, NULL );
GLenum error = glGetError();
if( error != GL_NO_ERROR ) {
std::cout << "Error initializing App!" << gluErrorString( error ) << std::endl;
success = false;
}
return success;
}
bool Texture::load(std::string fileName)
{
bool success = true;
free();
int imgFlags = IMG_INIT_PNG | IMG_INIT_JPG;
if( !( IMG_Init( imgFlags ) & imgFlags ) ) {
std::cout << "SDL_image could not initialize! SDL_image Error: " << IMG_GetError() << std::endl;
success = false;
}
else {
mTextureSurface = IMG_Load(fileName.c_str());
if( mTextureSurface == nullptr ) {
std::cout << "Unable to load image " << fileName.c_str() << " SDL Error: " << SDL_GetError() << std::endl;
success = false;
}
else {
mWidth = mTextureSurface->w;
mHeight = mTextureSurface->h;
glGenTextures( 1, &mTexture );
glBindTexture( GL_TEXTURE_2D, mTexture );
GLenum format = GL_RGB;
if (isBMP(fileName)) {
format = GL_BGR;
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, mWidth, mHeight, 0, format, GL_UNSIGNED_BYTE, mTextureSurface->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glBindTexture( GL_TEXTURE_2D, 0 );
//Check for error
GLenum error = glGetError();
if( error != GL_NO_ERROR ) {
std::cout << "Error loading texture" << gluErrorString( error ) << std::endl;
success = false;
}
success = init();
}
}
return success;
}
bool Texture::load(std::string fileName, vec3 const & colorKey )
{
bool success = true;
free();
int imgFlags = IMG_INIT_PNG | IMG_INIT_JPG;
if( !( IMG_Init( imgFlags ) & imgFlags ) ) {
std::cout << "SDL_image could not initialize! SDL_image Error: " << IMG_GetError() << std::endl;
success = false;
}
else {
mTextureSurface = IMG_Load( fileName.c_str() );
if( mTextureSurface == nullptr ) {
std::cout << "Unable to load image " << fileName.c_str() << " SDL Error: " << SDL_GetError() << std::endl;
success = false;
}
else {
GLenum format = GL_RGBA;
if (isBMP(fileName)) {
format = GL_BGRA;
}
SDL_SetColorKey( mTextureSurface, SDL_TRUE, SDL_MapRGB( mTextureSurface->format, colorKey.x, colorKey.y, colorKey.z ) );
mWidth = mTextureSurface->w;
mHeight = mTextureSurface->h;
glGenTextures( 1, &mTexture );
glBindTexture( GL_TEXTURE_2D, mTexture );
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, mWidth, mHeight, 0, format, GL_UNSIGNED_BYTE, mTextureSurface->pixels );
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture( GL_TEXTURE_2D, 0 );
//Check for error
GLenum error = glGetError();
if( error != GL_NO_ERROR ) {
std::cout << "Error loading texture" << gluErrorString( error ) << std::endl;
success = false;
}
success = init();
}
}
return success;
}
void Texture::free() {
if( mTexture != 0 ) {
glDeleteTextures( 1, &mTexture );
mTexture = 0;
}
if (mTextureSurface != nullptr) {
SDL_FreeSurface(mTextureSurface);
mTextureSurface = nullptr;
}
if (mProgramID != 0) glDeleteProgram( mProgramID );
for(uint i = 0; i < mVBO.size(); ++i) {
glDeleteBuffers( 1, &mVBO[0] );
}
for(uint i = 0; i < mIBO.size(); ++i) {
glDeleteBuffers( 1, &mIBO[0] );
}
}
void Texture::bind()
{
glBindTexture(GL_TEXTURE_2D, mTexture);
}
void Texture::unbind()
{
glBindTexture(GL_TEXTURE_2D, 0);
}
void Texture::draw()
{
glUseProgram( mProgramID );
bind();
GLuint attributeLocation = mVertexShader[0].setAttribute("LVertexPos2D");
glEnableVertexAttribArray( attributeLocation );
glBindBuffer( GL_ARRAY_BUFFER, mVBO[0] );
glVertexAttribPointer( attributeLocation, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), NULL );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, mIBO[0] );
glDrawElements( GL_TRIANGLE_FAN, 4, GL_UNSIGNED_INT, NULL );
mVertexShader[0].unsetAttribute(attributeLocation);
unbind();
glUseProgram( NULL );
}
bool Texture::isBMP(std::string fileName)
{
bool isB = fileName.at(fileName.size() - 3) == 'b' || fileName.at(fileName.size() - 3) == 'B';
bool isM = fileName.at(fileName.size() - 2) == 'm' || fileName.at(fileName.size() - 2) == 'M';
bool isP = fileName.at(fileName.size() - 1) == 'p' || fileName.at(fileName.size() - 1) == 'P';
return isB && isM && isP;
} | [
"alexgg.developer@gmail.com"
] | alexgg.developer@gmail.com |
fa91af7654a8ad07b6ff07b4ec937bc0207fe6a4 | 2b82c7a6b694ff9a99604fee2037df4ecc966df3 | /src/curvaturetensor.cpp | aaa3f2a6340bf92394ebd49d1298e0904e3dcbd5 | [] | no_license | juliendvl/modeleur-bmesh | b983bb534078c2bcdeddf2b3a3876d0998346b67 | 027f5ceb8c4d931b25e48f2f3bd4ba9d43f74f3c | refs/heads/master | 2021-01-10T09:28:24.569504 | 2015-07-01T16:44:39 | 2015-07-01T16:44:39 | 35,996,303 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,481 | cpp | #include <iostream>
#include <Eigen/Eigenvalues>
#include "curvaturetensor.h"
#include "mathutils.h"
using namespace std;
using namespace Eigen;
using OpenMesh::Vec2f;
///////////////////////////////////////////////////////////////////////////////
CurvatureTensor::CurvatureTensor(BMesh *m) : m(m) {}
///////////////////////////////////////////////////////////////////////////////
bool CurvatureTensor::compute(const BMesh::VertexHandle &p,
const vector<BMesh::VertexHandle> &neighbors)
{
this->p = p;
this->neighbors = neighbors;
curvatures.clear();
directions.clear();
Vector3f px = OMEigen::toEigen(m->point(p));
Vector3f nx = OMEigen::toEigen(m->normal(p));
// We construct the tangent plane
tp = getTangentPlane(px, nx);
// We only need 2 neighbors to compute Weingarten matrix
Vector3f n0 = OMEigen::toEigen(m->normal(neighbors[1]));
Vector3f n1 = OMEigen::toEigen(m->normal(neighbors[2]));
Vector3f p0 = OMEigen::toEigen(m->point(neighbors[1]));
Vector3f p1 = OMEigen::toEigen(m->point(neighbors[2]));
float n0u = (n0 - nx).dot(tp[0]);
float n0v = (n0 - nx).dot(tp[1]);
float n1u = (n1 - nx).dot(tp[0]);
Vector3f pe0 = MathUtils::projectVector(p0 - px, nx);
Vector3f pe1 = MathUtils::projectVector(p1 - px, nx);
float e0u = pe0.dot(tp[0]);
float e0v = pe0.dot(tp[1]);
float e1u = pe1.dot(tp[0]);
float e1v = pe1.dot(tp[1]);
// We construct the linear system
Matrix3f A;
A << e0u, e0v, 0,
0, e0u + e1u, e0v + e1v,
e1u, e1v, 0;
Vector3f B;
B << n0u, n0v, n1u;
// We solve the linear system
Vector3f X = A.jacobiSvd(ComputeFullU | ComputeFullV).solve(B);
// We construct the Weingarten matrix
Matrix2f W;
W << X(0), X(1), X(1), X(2);
// We set curvatures and directions
EigenSolver<Matrix2f> es(W);
Vector2cf eval = es.eigenvalues();
curvatures.push_back(eval[0].real());
curvatures.push_back(eval[1].real());
Matrix2cf evec = es.eigenvectors();
directions.push_back(Vector2f(evec(0,0).real(), evec(0,1).real()));
directions.push_back(Vector2f(evec(1,0).real(), evec(1,1).real()));
directions[0].normalize();
directions[1].normalize();
return true;
}
///////////////////////////////////////////////////////////////////////////////
vector<float> CurvatureTensor::getCurvatures() const {
return this->curvatures;
}
///////////////////////////////////////////////////////////////////////////////
vector<Vector2f> CurvatureTensor::getDirections() const {
return this->directions;
}
///////////////////////////////////////////////////////////////////////////////
vector<Vector3f> CurvatureTensor::getTangentPlane(const Vector3f &px,
const Vector3f &nx)
{
vector<Vector3f> res;
// First, we must project ont neighbor in the tangent plane
Vector3f pnbor = OMEigen::toEigen(m->point(neighbors[0]));
pnbor = MathUtils::projectPoint(px, pnbor, nx);
// "X" axis
Vector3f xAxis = pnbor - px;
xAxis.normalize();
res.push_back(xAxis);
// "Y" axis
Vector3f yAxis = nx.cross(xAxis);
yAxis.normalize();
res.push_back(yAxis);
res.push_back(nx);
return res;
}
///////////////////////////////////////////////////////////////////////////////
vector<Vector3f> CurvatureTensor::tangentPlane() const {
return tp;
}
| [
"julien.daval@ensimag.grenoble-inp.fr"
] | julien.daval@ensimag.grenoble-inp.fr |
12f03b6af4f0f2c1ed2af7f4e6efe7c9f6eaeaa2 | 21f5356e9fd0b3ab9ee7a5c54e30fd94bb660ee4 | /win32/src/win32crypt/PyCTL_CONTEXT.cpp | 805495386aefe5e81b21722db47ca65515463ab0 | [] | no_license | chevah/pywin32 | 90850232a557ecf054bc316e324aaf60188f2cca | d4ff0b440147ab65f1945991e81163fb1cf1ceaf | refs/heads/master | 2020-03-29T09:46:04.465546 | 2014-10-24T09:11:17 | 2014-10-24T09:11:17 | 25,680,336 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,881 | cpp | // @doc
#include "win32crypt.h"
// @object PyCTL_CONTEXT|Object containing a Certificate Trust List
struct PyMethodDef PyCTL_CONTEXT::methods[] = {
// @pymeth CertFreeCTLContext|Closes the context handle
{"CertFreeCTLContext", PyCTL_CONTEXT::PyCertFreeCTLContext, METH_NOARGS},
// @pymeth CertEnumCTLContextProperties|Lists property id's for the context
{"CertEnumCTLContextProperties", PyCTL_CONTEXT::PyCertEnumCTLContextProperties, METH_NOARGS},
// @pymeth CertEnumSubjectInSortedCTL|Retrieves trusted subjects contained in CTL
{"CertEnumSubjectInSortedCTL", PyCTL_CONTEXT::PyCertEnumSubjectInSortedCTL, METH_NOARGS},
// @pymeth CertDeleteCTLFromStore|Removes the CTL from the store that it is contained in
{"CertDeleteCTLFromStore", PyCTL_CONTEXT::PyCertDeleteCTLFromStore, METH_NOARGS},
// @pymeth CertSerializeCTLStoreElement|Serializes the CTL and its properties
{"CertSerializeCTLStoreElement", (PyCFunction)PyCTL_CONTEXT::PyCertSerializeCTLStoreElement, METH_KEYWORDS|METH_VARARGS},
{NULL}
};
PyTypeObject PyCTL_CONTEXTType =
{
PYWIN_OBJECT_HEAD
"PyCTL_CONTEXT",
sizeof(PyCTL_CONTEXT),
0,
PyCTL_CONTEXT::deallocFunc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0,
0, /* tp_call */
0, /* tp_str */
PyCTL_CONTEXT::getattro,
PyCTL_CONTEXT::setattro,
0, // PyBufferProcs *tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
0, // tp_doc
0, // traverseproc tp_traverse
0, // tp_clear
0, // richcmpfunc tp_richcompare
0, // tp_weaklistoffset
0, // getiterfunc tp_iter
0, // iternextfunc tp_iternext
PyCTL_CONTEXT::methods,
PyCTL_CONTEXT::members
};
struct PyMemberDef PyCTL_CONTEXT::members[] = {
// @prop int|HCTL_CONTEXT|Raw message handle
{"PCCTL_CONTEXT", T_OBJECT, offsetof(PyCTL_CONTEXT, obctl_context), READONLY, "Integet context handle"},
{NULL} /* Sentinel */
};
int PyCTL_CONTEXT::setattro(PyObject *self, PyObject *obname, PyObject *v)
{
return PyObject_GenericSetAttr(self, obname, v);
}
PyObject *PyCTL_CONTEXT::getattro(PyObject *self, PyObject *obname)
{
return PyObject_GenericGetAttr(self,obname);
}
BOOL PyWinObject_AsCTL_CONTEXT(PyObject *ob, PCCTL_CONTEXT *ppctl_context, BOOL bNoneOK)
{
if (bNoneOK && (ob==Py_None)){
*ppctl_context=NULL;
return true;
}
if (ob->ob_type!=&PyCTL_CONTEXTType){
PyErr_SetString(PyExc_TypeError,"Object must be of type PyCTL_CONTEXT");
return FALSE;
}
*ppctl_context=((PyCTL_CONTEXT *)ob)->GetCTL_CONTEXT();
return TRUE;
}
PyObject *PyWinObject_FromCTL_CONTEXT(PCCTL_CONTEXT pcc)
{
if (pcc==NULL){
Py_INCREF(Py_None);
return Py_None;
}
PyObject *ret = new PyCTL_CONTEXT(pcc);
if (ret==NULL)
PyErr_SetString(PyExc_MemoryError, "PyWinObject_FromCTL_CONTEXT: Unable to create PyCTL_CONTEXT instance");
return ret;
}
PyCTL_CONTEXT::~PyCTL_CONTEXT(void)
{
if (pctl_context!=NULL)
CertFreeCTLContext(pctl_context);
Py_XDECREF(this->obctl_context);
}
void PyCTL_CONTEXT::deallocFunc(PyObject *ob)
{
delete (PyCTL_CONTEXT *)ob;
}
PyCTL_CONTEXT::PyCTL_CONTEXT(PCCTL_CONTEXT pcc)
{
ob_type = &PyCTL_CONTEXTType;
_Py_NewReference(this);
this->pctl_context=pcc;
this->obctl_context=PyLong_FromVoidPtr((void *)pcc);
this->obdummy=NULL;
}
// @pymethod |PyCTL_CONTEXT|CertFreeCTLContext|Closes the CTL handle
PyObject *PyCTL_CONTEXT::PyCertFreeCTLContext(PyObject *self, PyObject *args)
{
PCCTL_CONTEXT pcc=((PyCTL_CONTEXT *)self)->GetCTL_CONTEXT();
if(!CertFreeCTLContext(pcc))
return PyWin_SetAPIError("CertFreeCTLContext");
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod (int,...)|PyCTL_CONTEXT|CertEnumCTLContextProperties|Lists property id's for the context
PyObject *PyCTL_CONTEXT::PyCertEnumCTLContextProperties(PyObject *self, PyObject *args)
{
PCCTL_CONTEXT pctl=((PyCTL_CONTEXT *)self)->GetCTL_CONTEXT();
PyObject *ret_item=NULL;
DWORD err=0, prop=0;
PyObject *ret=PyList_New(0);
if (ret==NULL)
return NULL;
while (TRUE){
prop=CertEnumCTLContextProperties(pctl, prop);
if (prop == 0)
break;
ret_item=PyLong_FromUnsignedLong(prop);
if ((ret_item==NULL) || (PyList_Append(ret, ret_item)==-1)){
Py_XDECREF(ret_item);
Py_DECREF(ret);
ret=NULL;
break;
}
Py_DECREF(ret_item);
}
return ret;
}
// @pymethod ((str,str),...)|PyCTL_CONTEXT|CertEnumSubjectInSortedCTL|Retrieves trusted subjects contained in CRL
// @rdesc Returns a sequence of tuples containing two strings (SubjectIdentifier, EncodedAttributes)
PyObject *PyCTL_CONTEXT::PyCertEnumSubjectInSortedCTL(PyObject *self, PyObject *args)
{
PCCTL_CONTEXT pctl=((PyCTL_CONTEXT *)self)->GetCTL_CONTEXT();
void *ctxt=NULL;
CRYPT_DER_BLOB subject, attr;
PyObject *ret_item=NULL;
PyObject *ret=PyList_New(0);
if (ret==NULL)
return NULL;
while (CertEnumSubjectInSortedCTL(pctl, &ctxt, &subject, &attr)){
ret_item=Py_BuildValue("NN",
PyString_FromStringAndSize((char *)subject.pbData, subject.cbData),
PyString_FromStringAndSize((char *)attr.pbData, attr.cbData));
if ((ret_item==NULL) || (PyList_Append(ret, ret_item)==-1)){
Py_XDECREF(ret_item);
Py_DECREF(ret);
ret=NULL;
break;
}
Py_DECREF(ret_item);
}
return ret;
}
// @pymethod |PyCTL_CONTEXT|CertDeleteCTLFromStore|Removes the CTL from the store that it is contained in
PyObject *PyCTL_CONTEXT::PyCertDeleteCTLFromStore(PyObject *self, PyObject *args)
{
PCCTL_CONTEXT pctl=((PyCTL_CONTEXT *)self)->GetCTL_CONTEXT();
if (!CertDeleteCTLFromStore(pctl))
return PyWin_SetAPIError("CertDeleteCTLFromStore");
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod string|PyCTL_CONTEXT|CertSerializeCTLStoreElement|Serializes the CTL and its properties
PyObject *PyCTL_CONTEXT::PyCertSerializeCTLStoreElement(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *keywords[]={"Flags", NULL};
PyObject *ret=NULL;
DWORD flags=0, bufsize=0;
PCCTL_CONTEXT pctl=((PyCTL_CONTEXT *)self)->GetCTL_CONTEXT();
BYTE *buf=NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|k:CertSerializeCTLStoreElement", keywords,
&flags)) // @pyparm int|Flags|0|Reserved, use only 0 if passed in
return NULL;
if (!CertSerializeCTLStoreElement(pctl, flags, buf, &bufsize))
return PyWin_SetAPIError("CertSerializeCTLStoreElement");
buf=(BYTE *)malloc(bufsize);
if (buf==NULL)
return PyErr_Format(PyExc_MemoryError, "Unable to allocate %d bytes", bufsize);
if (!CertSerializeCTLStoreElement(pctl, flags, buf, &bufsize))
PyWin_SetAPIError("CertSerializeCTLStoreElement");
else
ret=PyString_FromStringAndSize((char *)buf, bufsize);
free(buf);
return ret;
}
| [
"adi.roiban@chevah.com"
] | adi.roiban@chevah.com |
6c7635822a95cb81406f8dacc32328f49a6a9ca5 | 3ae5046511f265e9ba1be9008e4d22a51601b6e8 | /Source/SideScroller1/World/ColorSwitch.h | 5622c927401126a280c37da2e6f206037607bcc8 | [] | no_license | Daveiac/Master | 3429532d1451ff2f034d8164029e9abfd5ba5300 | d9bdf5d8de0ca03f7312814c846b50ef41a05c76 | refs/heads/master | 2021-01-12T13:54:50.529112 | 2016-06-17T18:54:36 | 2016-06-17T18:54:36 | 54,957,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Switch.h"
#include "ColorSwitch.generated.h"
/**
*
*/
UCLASS()
class SIDESCROLLER1_API AColorSwitch : public ASwitch
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, Category = "ColorBox")
int32 Channel;
virtual void Activate() override;
virtual void Deactivate() override;
void Toggle();
};
| [
"daveiac@hotmail.com"
] | daveiac@hotmail.com |
8c8e85d96a99520c24de828a2df78b3979bb6d8a | a4138202e6d036691bc12e8e868b911bcd6fe641 | /Greedy/kbookings.cpp | 9b55f890d2bf65159a627b64af789dcbd71953c3 | [] | no_license | Irhu007/Programming | c76dc88f3acbdff0f11cc5ae0a615daa853eb2f9 | 5b7053c3f7b6196438b881458a8be806b74ecbe4 | refs/heads/master | 2020-03-22T13:32:38.883895 | 2018-07-18T10:57:13 | 2018-07-18T10:57:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 805 | cpp | #include <bits/stdc++.h>
using namespace std;
bool areBookingsPossible(int arrival[], int departure[], int n, int k)
{
int last_date= departure[0];
int j=0;
int room=1;
for(int i = 1;i<n;i++)
{
if(arrival[i]>last_date)
{
last_date = departure[i];
j=i;
}
else
{
if(last_date>arrival[i])
room++;
else
{
j=j+1;
last_date = departure[j];
}
}
}
//cout<<room<<" ";
return room>k?0:1;
}
int main()
{
int arrival[] = { 1, 3, 5, 7 };
int departure[] = { 2, 8, 8, 10 };
int n = sizeof(arrival) / sizeof(arrival[0]);
cout << (areBookingsPossible(arrival,
departure, n, 1) ? "Yes\n" : "No\n");
return 0;
}
| [
"amann12997@gmail.com"
] | amann12997@gmail.com |
e80c86eb6b18ae6dd4bd766b16320fdb39128e18 | 94e5a9e157d3520374d95c43fe6fec97f1fc3c9b | /@DOC by DIPTA/Old/graph/flow.cpp | 29832badc954e1633f8356d2aeb2b39c8eea92a3 | [
"MIT"
] | permissive | dipta007/Competitive-Programming | 0127c550ad523884a84eb3ea333d08de8b4ba528 | 998d47f08984703c5b415b98365ddbc84ad289c4 | refs/heads/master | 2021-01-21T14:06:40.082553 | 2020-07-06T17:40:46 | 2020-07-06T17:40:46 | 54,851,014 | 8 | 4 | null | 2020-05-02T13:14:41 | 2016-03-27T22:30:02 | C++ | UTF-8 | C++ | false | false | 4,104 | cpp | struct node {
int x, y, next, cap, cost;
};
/**
1. Clear graph
2. Add edge
3. Assign source and sink
4. Pass highestNumberOfNode to maxFlow() or minCostMaxFlow()
*/
///Try to make size of edge array as large possible
const int NODE=101,EDGE=50001;
struct FLOW {
int source, sink;
int head[NODE];
void clear() {
e = 0;
clr_(head);
}
node edge[EDGE]; int e;
///cap holo max koto flow deoa jabe
///cap2 holo koto flow deoa hoise
void addEdge ( int u, int v, int cap, int cap2, int cost ) {
edge[e].x = u; edge[e].y = v; edge[e].cap = cap; edge[e].cost = cost;
edge[e].next = head[u]; head[u] = e; e++;
edge[e].x = v; edge[e].y = u; edge[e].cap = cap; edge[e].cost = -cost;
edge[e].next = head[v]; head[v] = e; e++;
}
int vis[NODE], q[NODE], now[NODE];
bool bfs ( ) {
memset ( vis, -1, sizeof vis );
vis[source] = 0;
int ini = 0, qend = 0;
q[qend++] = source;
while ( ini < qend && vis[sink] == -1 ) {
int s = q[ini++];
int i;
for (i=head[s];i!=-1;i= edge[i].next){
int t = edge[i].y;
if ( vis[t] == -1 && edge[i].cap){
vis[t] = vis[s] + 1;
q[qend++] = t;
}
}
}
if ( vis[sink] != -1 ) return true;
else return false;
}
int dfs ( int s, int f ) {
if ( f == 0 ) return 0;
if ( s == sink ) return f;
for ( int &i=now[s];i!=-1;i=edge[i].next){
int t = edge[i].y;
if ( vis[s] + 1 != vis[t] ) continue;
int pushed=dfs(t,min(f,edge[i].cap));
if ( pushed ) {
edge[i].cap -= pushed;
edge[i^1].cap += pushed;
return pushed;
}
}
return 0;
}
int maxFlow ( int highestNumberOfNode, int flow ) {
int res = 0;
while ( 1 ) {
if ( flow == 0 ) break;
if ( bfs () == false ) break;
int i;
for ( i=0;i<=highestNumberOfNode;i++)now[i]= head[i];
while (int pushed=dfs(source,flow ) ) {
res += pushed; ///Can overflow depending on Max Flow
flow -= pushed;
}
}
return res;
}
int inq[NODE], par[NODE], record[NODE];
int minCostFlow ( int highestNumberOfNode ) {
int res = 0, i, j, k, fl = 0;
while ( 1 ) {
for ( i = 0; i <= highestNumberOfNode; i++ ) vis[i] = inf;
vis[source] = 0;
deque < int > dq;
dq.pb ( source );
while ( !dq.empty() ) {
int s = dq.front(); dq.pop_front();
inq[s] = 0;
for ( i = head[s]; i != -1; i = edge[i].next ) {
int t = edge[i].y;
if ( edge[i].cap ) {
if ( vis[s] + edge[i].cost < vis[t] ) {
vis[t] = vis[s] + edge[i].cost;
par[t] = s;
record[t] = i;
if ( inq[t] == 0 ) {
inq[t] = 1;
if ( dq.empty() == false && vis[dq.front()] > vis[t] )
dq.push_front( t );
else dq.pb ( t );
}
}
}
}
}
//if ( vis[sink] > 0 ) break; ///Cost Getting minimized, Change Here
if ( vis[sink] == inf ) break; //Flow getting maximized. Either this, or the one above
fl++; ///Total flow
res += vis[sink]; ///Cost of Flow
for ( i = sink; i != source; i = par[i] ) { //Travel from sink to source
int t = record[i]; //Record which edge was used to travel to t
edge[t].cap--;
edge[t^1].cap++;
}
}
return res; ///Min cost of max flow
}
}graph;
| [
"iamdipta@gmail.com"
] | iamdipta@gmail.com |
d20de5c1fd31bf863c7f5a24ac8637b79032bb51 | ea1328695989667c9ab168facfa1095ffe55639c | /libs/harfbuzz-ng/src/hb-ot-shape-complex-arabic-fallback.hh | a77f24ec849b6b0b9a9a11b79709d3619ea22fb9 | [
"LicenseRef-scancode-other-permissive",
"MIT-Modern-Variant",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | amarullz/libaroma | c075058d9e434bdd2faf6ed1d3e3e008666f3146 | cdbe5847d967ae85c442eaf2db7beb08a8cf6713 | refs/heads/master | 2022-12-22T16:09:39.500801 | 2022-12-15T02:37:18 | 2022-12-15T02:37:18 | 29,760,977 | 51 | 33 | Apache-2.0 | 2022-07-11T02:47:17 | 2015-01-24T01:17:06 | C | UTF-8 | C++ | false | false | 12,325 | hh | /*
* Copyright © 2012 Google, Inc.
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Google Author(s): Behdad Esfahbod
*/
#ifndef HB_OT_SHAPE_COMPLEX_ARABIC_FALLBACK_HH
#define HB_OT_SHAPE_COMPLEX_ARABIC_FALLBACK_HH
#include "hb-private.hh"
#include "hb-ot-shape-private.hh"
#include "hb-ot-layout-gsub-table.hh"
/* Features ordered the same as the entries in shaping_table rows,
* followed by rlig. Don't change. */
static const hb_tag_t arabic_fallback_features[] =
{
HB_TAG('i','n','i','t'),
HB_TAG('m','e','d','i'),
HB_TAG('f','i','n','a'),
HB_TAG('i','s','o','l'),
HB_TAG('r','l','i','g'),
};
static OT::SubstLookup *
arabic_fallback_synthesize_lookup_single (const hb_ot_shape_plan_t *plan HB_UNUSED,
hb_font_t *font,
unsigned int feature_index)
{
OT::GlyphID glyphs[SHAPING_TABLE_LAST - SHAPING_TABLE_FIRST + 1];
OT::GlyphID substitutes[SHAPING_TABLE_LAST - SHAPING_TABLE_FIRST + 1];
unsigned int num_glyphs = 0;
/* Populate arrays */
for (hb_codepoint_t u = SHAPING_TABLE_FIRST; u < SHAPING_TABLE_LAST + 1; u++)
{
hb_codepoint_t s = shaping_table[u - SHAPING_TABLE_FIRST][feature_index];
hb_codepoint_t u_glyph, s_glyph;
if (!s ||
!hb_font_get_glyph (font, u, 0, &u_glyph) ||
!hb_font_get_glyph (font, s, 0, &s_glyph) ||
u_glyph == s_glyph ||
u_glyph > 0xFFFFu || s_glyph > 0xFFFFu)
continue;
glyphs[num_glyphs].set (u_glyph);
substitutes[num_glyphs].set (s_glyph);
num_glyphs++;
}
if (!num_glyphs)
return NULL;
/* Bubble-sort!
* May not be good-enough for presidential candidate interviews, but good-enough for us... */
hb_bubble_sort (&glyphs[0], num_glyphs, OT::GlyphID::cmp, &substitutes[0]);
OT::Supplier<OT::GlyphID> glyphs_supplier (glyphs, num_glyphs);
OT::Supplier<OT::GlyphID> substitutes_supplier (substitutes, num_glyphs);
/* Each glyph takes four bytes max, and there's some overhead. */
char buf[(SHAPING_TABLE_LAST - SHAPING_TABLE_FIRST + 1) * 4 + 128];
OT::hb_serialize_context_t c (buf, sizeof (buf));
OT::SubstLookup *lookup = c.start_serialize<OT::SubstLookup> ();
bool ret = lookup->serialize_single (&c,
OT::LookupFlag::IgnoreMarks,
glyphs_supplier,
substitutes_supplier,
num_glyphs);
c.end_serialize ();
/* TODO sanitize the results? */
return ret ? c.copy<OT::SubstLookup> () : NULL;
}
static OT::SubstLookup *
arabic_fallback_synthesize_lookup_ligature (const hb_ot_shape_plan_t *plan HB_UNUSED,
hb_font_t *font)
{
OT::GlyphID first_glyphs[ARRAY_LENGTH_CONST (ligature_table)];
unsigned int first_glyphs_indirection[ARRAY_LENGTH_CONST (ligature_table)];
unsigned int ligature_per_first_glyph_count_list[ARRAY_LENGTH_CONST (first_glyphs)];
unsigned int num_first_glyphs = 0;
/* We know that all our ligatures are 2-component */
OT::GlyphID ligature_list[ARRAY_LENGTH_CONST (first_glyphs) * ARRAY_LENGTH_CONST(ligature_table[0].ligatures)];
unsigned int component_count_list[ARRAY_LENGTH_CONST (ligature_list)];
OT::GlyphID component_list[ARRAY_LENGTH_CONST (ligature_list) * 1/* One extra component per ligature */];
unsigned int num_ligatures = 0;
/* Populate arrays */
/* Sort out the first-glyphs */
for (unsigned int first_glyph_idx = 0; first_glyph_idx < ARRAY_LENGTH (first_glyphs); first_glyph_idx++)
{
hb_codepoint_t first_u = ligature_table[first_glyph_idx].first;
hb_codepoint_t first_glyph;
if (!hb_font_get_glyph (font, first_u, 0, &first_glyph))
continue;
first_glyphs[num_first_glyphs].set (first_glyph);
ligature_per_first_glyph_count_list[num_first_glyphs] = 0;
first_glyphs_indirection[num_first_glyphs] = first_glyph_idx;
num_first_glyphs++;
}
hb_bubble_sort (&first_glyphs[0], num_first_glyphs, OT::GlyphID::cmp, &first_glyphs_indirection[0]);
/* Now that the first-glyphs are sorted, walk again, populate ligatures. */
for (unsigned int i = 0; i < num_first_glyphs; i++)
{
unsigned int first_glyph_idx = first_glyphs_indirection[i];
for (unsigned int second_glyph_idx = 0; second_glyph_idx < ARRAY_LENGTH (ligature_table[0].ligatures); second_glyph_idx++)
{
hb_codepoint_t second_u = ligature_table[first_glyph_idx].ligatures[second_glyph_idx].second;
hb_codepoint_t ligature_u = ligature_table[first_glyph_idx].ligatures[second_glyph_idx].ligature;
hb_codepoint_t second_glyph, ligature_glyph;
if (!second_u ||
!hb_font_get_glyph (font, second_u, 0, &second_glyph) ||
!hb_font_get_glyph (font, ligature_u, 0, &ligature_glyph))
continue;
ligature_per_first_glyph_count_list[i]++;
ligature_list[num_ligatures].set (ligature_glyph);
component_count_list[num_ligatures] = 2;
component_list[num_ligatures].set (second_glyph);
num_ligatures++;
}
}
if (!num_ligatures)
return NULL;
OT::Supplier<OT::GlyphID> first_glyphs_supplier (first_glyphs, num_first_glyphs);
OT::Supplier<unsigned int > ligature_per_first_glyph_count_supplier (ligature_per_first_glyph_count_list, num_first_glyphs);
OT::Supplier<OT::GlyphID> ligatures_supplier (ligature_list, num_ligatures);
OT::Supplier<unsigned int > component_count_supplier (component_count_list, num_ligatures);
OT::Supplier<OT::GlyphID> component_supplier (component_list, num_ligatures);
/* 16 bytes per ligature ought to be enough... */
char buf[ARRAY_LENGTH_CONST (ligature_list) * 16 + 128];
OT::hb_serialize_context_t c (buf, sizeof (buf));
OT::SubstLookup *lookup = c.start_serialize<OT::SubstLookup> ();
bool ret = lookup->serialize_ligature (&c,
OT::LookupFlag::IgnoreMarks,
first_glyphs_supplier,
ligature_per_first_glyph_count_supplier,
num_first_glyphs,
ligatures_supplier,
component_count_supplier,
component_supplier);
c.end_serialize ();
/* TODO sanitize the results? */
return ret ? c.copy<OT::SubstLookup> () : NULL;
}
static OT::SubstLookup *
arabic_fallback_synthesize_lookup (const hb_ot_shape_plan_t *plan,
hb_font_t *font,
unsigned int feature_index)
{
if (feature_index < 4)
return arabic_fallback_synthesize_lookup_single (plan, font, feature_index);
else
return arabic_fallback_synthesize_lookup_ligature (plan, font);
}
#define ARABIC_FALLBACK_MAX_LOOKUPS 5
struct arabic_fallback_plan_t
{
ASSERT_POD ();
unsigned int num_lookups;
bool free_lookups;
hb_mask_t mask_array[ARABIC_FALLBACK_MAX_LOOKUPS];
OT::SubstLookup *lookup_array[ARABIC_FALLBACK_MAX_LOOKUPS];
hb_ot_layout_lookup_accelerator_t accel_array[ARABIC_FALLBACK_MAX_LOOKUPS];
};
static const arabic_fallback_plan_t arabic_fallback_plan_nil = {};
#if (defined(_WIN32) || defined(__CYGWIN__)) && !defined(HB_NO_WIN1256)
#define HB_WITH_WIN1256
#endif
#ifdef HB_WITH_WIN1256
#include "hb-ot-shape-complex-arabic-win1256.hh"
#endif
struct ManifestLookup {
OT::Tag tag;
OT::OffsetTo<OT::SubstLookup> lookupOffset;
};
typedef OT::ArrayOf<ManifestLookup> Manifest;
static bool
arabic_fallback_plan_init_win1256 (arabic_fallback_plan_t *fallback_plan,
const hb_ot_shape_plan_t *plan,
hb_font_t *font)
{
#ifdef HB_WITH_WIN1256
/* Does this font look like it's Windows-1256-encoded? */
hb_codepoint_t g;
if (!(hb_font_get_glyph (font, 0x0627u, 0, &g) && g == 199 /* ALEF */ &&
hb_font_get_glyph (font, 0x0644u, 0, &g) && g == 225 /* LAM */ &&
hb_font_get_glyph (font, 0x0649u, 0, &g) && g == 236 /* ALEF MAKSURA */ &&
hb_font_get_glyph (font, 0x064Au, 0, &g) && g == 237 /* YEH */ &&
hb_font_get_glyph (font, 0x0652u, 0, &g) && g == 250 /* SUKUN */))
return false;
const Manifest &manifest = reinterpret_cast<const Manifest&> (arabic_win1256_gsub_lookups.manifest);
ASSERT_STATIC (sizeof (arabic_win1256_gsub_lookups.manifestData) / sizeof (ManifestLookup)
<= ARABIC_FALLBACK_MAX_LOOKUPS);
/* TODO sanitize the table? */
unsigned j = 0;
unsigned int count = manifest.len;
for (unsigned int i = 0; i < count; i++)
{
fallback_plan->mask_array[j] = plan->map.get_1_mask (manifest[i].tag);
if (fallback_plan->mask_array[j])
{
fallback_plan->lookup_array[j] = const_cast<OT::SubstLookup*> (&(&manifest+manifest[i].lookupOffset));
if (fallback_plan->lookup_array[j])
{
fallback_plan->accel_array[j].init (*fallback_plan->lookup_array[j]);
j++;
}
}
}
fallback_plan->num_lookups = j;
fallback_plan->free_lookups = false;
return j > 0;
#else
return false;
#endif
}
static bool
arabic_fallback_plan_init_unicode (arabic_fallback_plan_t *fallback_plan,
const hb_ot_shape_plan_t *plan,
hb_font_t *font)
{
ASSERT_STATIC (ARRAY_LENGTH_CONST(arabic_fallback_features) <= ARABIC_FALLBACK_MAX_LOOKUPS);
unsigned int j = 0;
for (unsigned int i = 0; i < ARRAY_LENGTH(arabic_fallback_features) ; i++)
{
fallback_plan->mask_array[j] = plan->map.get_1_mask (arabic_fallback_features[i]);
if (fallback_plan->mask_array[j])
{
fallback_plan->lookup_array[j] = arabic_fallback_synthesize_lookup (plan, font, i);
if (fallback_plan->lookup_array[j])
{
fallback_plan->accel_array[j].init (*fallback_plan->lookup_array[j]);
j++;
}
}
}
fallback_plan->num_lookups = j;
fallback_plan->free_lookups = true;
return j > 0;
}
static arabic_fallback_plan_t *
arabic_fallback_plan_create (const hb_ot_shape_plan_t *plan,
hb_font_t *font)
{
arabic_fallback_plan_t *fallback_plan = (arabic_fallback_plan_t *) calloc (1, sizeof (arabic_fallback_plan_t));
if (unlikely (!fallback_plan))
return const_cast<arabic_fallback_plan_t *> (&arabic_fallback_plan_nil);
fallback_plan->num_lookups = 0;
fallback_plan->free_lookups = false;
/* Try synthesizing GSUB table using Unicode Arabic Presentation Forms,
* in case the font has cmap entries for the presentation-forms characters. */
if (arabic_fallback_plan_init_unicode (fallback_plan, plan, font))
return fallback_plan;
/* See if this looks like a Windows-1256-encoded font. If it does, use a
* hand-coded GSUB table. */
if (arabic_fallback_plan_init_win1256 (fallback_plan, plan, font))
return fallback_plan;
free (fallback_plan);
return const_cast<arabic_fallback_plan_t *> (&arabic_fallback_plan_nil);
}
static void
arabic_fallback_plan_destroy (arabic_fallback_plan_t *fallback_plan)
{
if (!fallback_plan || fallback_plan == &arabic_fallback_plan_nil)
return;
for (unsigned int i = 0; i < fallback_plan->num_lookups; i++)
if (fallback_plan->lookup_array[i])
{
fallback_plan->accel_array[i].fini ();
if (fallback_plan->free_lookups)
free (fallback_plan->lookup_array[i]);
}
free (fallback_plan);
}
static void
arabic_fallback_plan_shape (arabic_fallback_plan_t *fallback_plan,
hb_font_t *font,
hb_buffer_t *buffer)
{
OT::hb_apply_context_t c (0, font, buffer);
for (unsigned int i = 0; i < fallback_plan->num_lookups; i++)
if (fallback_plan->lookup_array[i]) {
c.set_lookup_mask (fallback_plan->mask_array[i]);
hb_ot_layout_substitute_lookup (&c,
*fallback_plan->lookup_array[i],
fallback_plan->accel_array[i]);
}
}
#endif /* HB_OT_SHAPE_COMPLEX_ARABIC_FALLBACK_HH */
| [
"amarullz@yahoo.com"
] | amarullz@yahoo.com |
acece0a9e6628529a6bcc6080544e77c3ea3e8ca | dd1645a024f8c17b033bb496df6d97c6539f6a54 | /base/inter/Expr.cpp | fc3484767251a00e4f460471d19e82eefd98718d | [] | no_license | shnere/CParserFinal | 741bd4fcedd91bac0f62f6518dca5aaa4286e882 | 899f9202193a8f3aefd9f7e997a932f0bf2022f6 | refs/heads/master | 2020-12-24T13:21:50.928950 | 2013-05-13T14:33:27 | 2013-05-13T14:33:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 953 | cpp | #include <sstream>
#include "Expr.hh"
std::stringstream out;
Expr::Expr(Token * tok, Type * p)
{
this->op = tok;
this->type = p;
}
Expr::~Expr()
{
}
Expr * Expr::gen()
{
return this;
}
Expr * Expr::reduce()
{
return this;
}
void Expr::jumping(int t, int f) {
this->emitjumps( this->toString(), t, f);
}
void Expr::emitjumps(std::string const &test, int t, int f)
{
if( t != 0 && f != 0){
out << t;
Node::emit("if "+ test +" goto "+ out.str());
out.str("");
out << f;
Node::emit("goto L"+out.str());
out.str("");
}else if( t != 0){
out << f;
Node::emit("if "+ test +" goto L "+ out.str());
out.str("");
} else if ( f != 0){
out << f;
Node::emit("iffalse " + test + " goto L" + out.str());
out.str("");
}
}
std::string const Expr::toString()
{
Word * w = dynamic_cast<Word *>(this->op);
if(w != 0) {
return w->toString();
} else {
return this->op->toString();
}
} | [
"alanrodriguezromero@gmail.com"
] | alanrodriguezromero@gmail.com |
1e5018b48d119ce45f302b78919feed1c2207eaf | ba1faf375c740ac60eb0b3ab334575466b6832b1 | /simple_app/library_dynamic/include/lib_dyn.h | a6b71a76037317f7c9561136c7b288531bfa4f24 | [
"MIT"
] | permissive | UNDEFINED-BEHAVIOR/More-Modern-CMake | a0529a6c352e387a48b65d278dcd1319195b1756 | e8d3e7376b889963eb5ed513c642c9e5f01b228b | refs/heads/master | 2021-07-14T17:51:07.233667 | 2020-07-29T14:16:17 | 2020-07-29T14:16:17 | 192,394,830 | 0 | 0 | null | 2019-06-17T18:02:32 | 2019-06-17T18:02:31 | null | UTF-8 | C++ | false | false | 195 | h | #pragma once
#ifndef NOEXPORT // Not declared
#define EXPORT_OR_NOT __declspec(dllexport)
#else
#define EXPORT_OR_NOT
#endif
class EXPORT_OR_NOT LibDynamic
{
public:
static void hi_fn();
};
| [
"bo.bantukulolarn@gmail.com"
] | bo.bantukulolarn@gmail.com |
b17eb7939de08d31f71aa2e655732ab5a965628f | 30f1ea99942ebeca2d91eb83b338f6bb0f8cda8a | /library/skia/ext/skia_utils_win.h | 5551db7705f2a27090fab240f00dedd1a894eae0 | [] | no_license | thinkincforeveryone/putty-nd6x | 8d085839b72ad07092eb1b194e0a9b397a8c8ffd | e3efbcdf22bd5323004dccccafd81ce11a359a2f | refs/heads/master | 2020-09-26T18:04:11.415969 | 2019-12-06T10:50:35 | 2019-12-06T10:50:35 | 226,306,231 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,167 | h |
#ifndef __skia_skia_utils_win_h__
#define __skia_skia_utils_win_h__
#pragma once
#include "SkColor.h"
struct SkIRect;
struct SkPoint;
struct SkRect;
typedef unsigned long DWORD;
typedef DWORD COLORREF;
typedef struct tagPOINT POINT;
typedef struct tagRECT RECT;
namespace skia
{
// Skia的点转换成Windows的POINT.
POINT SkPointToPOINT(const SkPoint& point);
// Windows的RECT转换成Skia的矩形.
SkRect RECTToSkRect(const RECT& rect);
// Windows的RECT转换成Skia的矩形.
// 两者使用相同的内存格式. 在skia_utils.cpp中通过COMPILE_ASSERT()
// 验证.
inline const SkIRect& RECTToSkIRect(const RECT& rect)
{
return reinterpret_cast<const SkIRect&>(rect);
}
// Skia的矩形转换成Windows的RECT.
// 两者使用相同的内存格式. 在skia_utils.cpp中通过COMPILE_ASSERT()
// 验证.
inline const RECT& SkIRectToRECT(const SkIRect& rect)
{
return reinterpret_cast<const RECT&>(rect);
}
// 转换COLORREFs(0BGR)到Skia支持的ARGB排列方式.
SkColor COLORREFToSkColor(COLORREF color);
// 转换ARGB到COLORREFs(0BGR).
COLORREF SkColorToCOLORREF(SkColor color);
} // namespace skia
#endif //__skia_skia_utils_win_h__ | [
"thinkinc@163.com"
] | thinkinc@163.com |
f197b2984e997da7ff0be7c18266d824913a92f8 | b6eabe93e2f67577f0c797a033a5d74a8a60cb17 | /Exercice1-1/main.cpp | d1d1c810b5f6f6c9fa085a4874e4413ee671972e | [] | no_license | gottburgm/INF1 | 9a884b25f5bbc992a854409809111b1752d86444 | eeab08da1a623b2102c55570387c5d52bfa3d19e | refs/heads/master | 2021-01-21T20:47:59.743569 | 2018-09-19T15:21:11 | 2018-09-19T15:21:11 | 69,362,560 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 508 | cpp | /*
-----------------------------------------------------------------------------------
Fichier : main.cpp
Auteur(s) : Robin Fournier
Date : 27.09.2016
But : Afficher un bonhomme dans la console
Remarque(s) : -
Compilateur : MinGW-g++ 4.8.1
-----------------------------------------------------------------------------------
*/
#include <iostream>
using namespace std;
/*
*
*/
int main() {
cout << " /////\n +-----+\n(| ° ° |)\n | ^ |\n | '-' |\n +-----+" << endl;
return 0;
}
| [
"fournier.robin@gmail.com"
] | fournier.robin@gmail.com |
ec6b8b34581bd0fe6cfbf062a8e1dfbe01934469 | 9c451121eaa5e0131110ad0b969d75d9e6630adb | /NIT/399.cpp | 1ce37a0869136c0c9362687f06bbdec31462b8d7 | [] | no_license | tokitsu-kaze/ACM-Solved-Problems | 69e16c562a1c72f2a0d044edd79c0ab949cc76e3 | 77af0182401904f8d2f8570578e13d004576ba9e | refs/heads/master | 2023-09-01T11:25:12.946806 | 2023-08-25T03:26:50 | 2023-08-25T03:26:50 | 138,472,754 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,743 | cpp | #include <bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/STACK:1024000000,1024000000")
#define mem(a,b) memset((a),(b),sizeof(a))
#define MP make_pair
#define pb push_back
#define fi first
#define se second
#define sz(x) (int)x.size()
#define all(x) x.begin(),x.end()
#define _GLIBCXX_PERMIT_BACKWARD_HASH
#include <ext/hash_map>
using namespace __gnu_cxx;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<ll,ll> PLL;
typedef vector<int> VI;
typedef vector<ll> VL;
struct str_hash{size_t operator()(const string& str)const{return __stl_hash_string(str.c_str());}};
const int INF=0x3f3f3f3f;
const ll LLINF=0x3f3f3f3f3f3f3f3f;
const double PI=acos(-1.0);
const double eps=1e-4;
const int MAX=1e5+10;
const ll mod=1e9+7;
/**************************************** head ****************************************/
ll dp[66][3];
ll gao(ll x)
{
vector<int> p;
if(x==-1) return 0;
while(1)
{
p.pb(x%2);
x/=2;
if(!x) break;
}
function<ll(int,int,int,int)> dfs=[&](int pos,int lead,int sta,int limt)->ll
{
if(pos==-1) return 1;
if(!limt&&!lead&&dp[pos][sta]!=-1) return dp[pos][sta];
ll res=0;
for(int i=(limt?p[pos]:1);~i;i--)
{
if(sta==1&&i==1) continue;
res+=dfs(pos-1,lead&&i==0&&pos,i,limt&&i==p[pos]);
}
if(!limt&&!lead) dp[pos][sta]=res;
return res;
};
return dfs(sz(p)-1,1,0,1);
}
int main()
{
ll n;
mem(dp,-1);
while(~scanf("%lld",&n))
{
ll l,r,mid;
l=1;
r=1e14;
while(l<r)
{
mid=(l+r)>>1;
if(gao(mid)-1<n) l=mid+1;
else r=mid;
}
// cout<<l<<" "<<gao(l)-1<<endl;
VI res;
while(1)
{
res.pb(l%2);
l/=2;
if(!l) break;
}
reverse(all(res));
for(auto it:res) printf("%d",it);
puts("");
}
return 0;
} | [
"861794979@qq.com"
] | 861794979@qq.com |
7a8035250e9cd87e177e86ed442f69c46ad2d1eb | e687e5b301ac021be140d11f88dc4b6309e78a48 | /Arrays/2. Maximum and Minimum.cpp | a89a13a9c01a386f85ea5c9abb1f6044f953c16c | [] | no_license | impolska742/dsa-450 | 00811d7b3f595085094e81cbef8ffaa272e686d8 | f26a61af920cea0f00dd51dc1f0a5dc8711eb10d | refs/heads/master | 2023-05-26T08:14:17.789961 | 2021-06-14T11:13:18 | 2021-06-14T11:13:18 | 372,952,500 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,889 | cpp | #include "useful.h"
// O(n) => O(N) + O(N)
// Time complexity => O(N)
// Space Complexity => O(1)
pair<int, int> naiveSolution(int arr[], int n) {
int minimumElement, maximumElement;
minimumElement = INT_MAX;
maximumElement = INT_MIN;
// For minimum element
for (int i = 0; i < n; i++) {
if (arr[i] < minimumElement) {
minimumElement = arr[i];
}
}
for (int i = 0; i < n; i++) {
if (arr[i] > maximumElement) {
maximumElement = arr[i];
}
}
return make_pair(minimumElement, maximumElement);
}
pair<int, int> singleSolution(int arr[], int n) {
int minimumElement, maximumElement;
minimumElement = INT_MAX;
maximumElement = INT_MIN;
// For minimum element
for (int i = 0; i < n; i++) {
if (arr[i] < minimumElement) {
minimumElement = arr[i];
}
if (arr[i] > maximumElement) {
maximumElement = arr[i];
}
}
return make_pair(minimumElement, maximumElement);
}
pair<int, int> secondMaxAndMinimum(int arr[], int n) {
int firstMin, secondMin, firstMax, secondMax;
firstMin = secondMin = INT_MAX;
firstMax = secondMax = INT_MIN;
// For minimum element
// 1 2 3 4 5
for (int i = 0; i < n; i++) {
if (arr[i] < firstMin) {
secondMin = firstMin;
firstMin = arr[i];
} else if (arr[i] < secondMin and arr[i] > firstMin) {
secondMin = arr[i];
}
else if (arr[i] > firstMax) {
secondMax = firstMax;
firstMax = arr[i];
} else if (arr[i] > secondMax and arr[i] < firstMax) {
secondMax = arr[i];
}
}
return make_pair(secondMin, secondMax);
}
int main(int argc, char const *argv[])
{
int arr[] = {4, 28, 56, 1, 3, 84};
int arr_size = sizeof(arr) / sizeof(arr[0]);
// 84 56
// 1 3
Display(arr, arr_size);
pair<int, int> p = naiveSolution(arr, arr_size);
pair<int, int> p2 = secondMaxAndMinimum(arr, arr_size);
cout << p.first << " " << p.second << endl;
cout << p2.first << " " << p2.second << endl;
return 0;
} | [
"vaibhav19bhardwaj@gmail.com"
] | vaibhav19bhardwaj@gmail.com |
3274f4755c1641ffb401e688a3d276a755b8ad6e | 71f2a62b3bb20eac1f3e0736a6de5f39d8fa8d5b | /src/codegen/cc_hash_table_proxy.cpp | ee3bb2a9a1b297524df7762b23761e8848b5e8cb | [
"Apache-2.0"
] | permissive | hanli32/peloton | aef49911fef78df2af621c5237f2835c63ae5a97 | 6afba19f530311a498a3e5e9160c98d1b8b93695 | refs/heads/master | 2021-01-11T18:04:42.584128 | 2017-05-06T02:41:02 | 2017-05-06T02:41:02 | 87,267,565 | 1 | 1 | null | 2017-04-27T03:08:18 | 2017-04-05T04:57:26 | C++ | UTF-8 | C++ | false | false | 5,585 | cpp | //===----------------------------------------------------------------------===//
//
// Peloton
//
// cc_hash_table_proxy.cpp
//
// Identification: src/codegen/cc_hash_table_proxy.cpp
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "codegen/cc_hash_table_proxy.h"
namespace peloton {
namespace codegen {
//===----------------------------------------------------------------------===//
// Return the LLVM type that matches the memory layout of our HashTable
//===----------------------------------------------------------------------===//
llvm::Type *CCHashTableProxy::GetType(CodeGen &codegen) {
static const std::string kHashTableTypeName = "peloton::CCHashTable";
// Check if the hash table type has been registered/cached in the module
// already
auto *hash_table_type = codegen.LookupTypeByName(kHashTableTypeName);
if (hash_table_type != nullptr) {
return hash_table_type;
}
// Define and register the type
std::vector<llvm::Type *> layout{
HashEntryProxy::GetType(codegen)->getPointerTo()->getPointerTo(),
codegen.Int64Type(), codegen.Int64Type(), codegen.Int64Type()};
hash_table_type = llvm::StructType::create(codegen.GetContext(), layout,
kHashTableTypeName);
return hash_table_type;
}
//===----------------------------------------------------------------------===//
// INIT PROXY
//===----------------------------------------------------------------------===//
const std::string &CCHashTableProxy::_Init::GetFunctionName() {
static const std::string kInitFnName =
#ifdef __APPLE__
"_ZN7peloton7codegen5utils11CCHashTable4InitEv";
#else
"_ZN7peloton7codegen5utils11CCHashTable4InitEv";
#endif
return kInitFnName;
}
llvm::Function *CCHashTableProxy::_Init::GetFunction(CodeGen &codegen) {
const std::string fn_name = GetFunctionName();
// Has the function already been registered?
llvm::Function *llvm_fn = codegen.LookupFunction(fn_name);
if (llvm_fn != nullptr) {
return llvm_fn;
}
// The function hasn't been registered, let's do it now
llvm::Type *ht_type = CCHashTableProxy::GetType(codegen)->getPointerTo();
llvm::FunctionType *fn_type =
llvm::FunctionType::get(codegen.VoidType(), ht_type);
return codegen.RegisterFunction(fn_name, fn_type);
};
//===----------------------------------------------------------------------===//
// DESTROY PROXY
//===----------------------------------------------------------------------===//
const std::string &CCHashTableProxy::_Destroy::GetFunctionName() {
static const std::string kStoreTupleFnName =
#ifdef __APPLE__
"_ZN7peloton7codegen5utils11CCHashTable7DestroyEv";
#else
"_ZN7peloton7codegen5utils11CCHashTable7DestroyEv";
#endif
return kStoreTupleFnName;
}
llvm::Function *CCHashTableProxy::_Destroy::GetFunction(CodeGen &codegen) {
const std::string fn_name = GetFunctionName();
// Has the function already been registered?
llvm::Function *llvm_fn = codegen.LookupFunction(fn_name);
if (llvm_fn != nullptr) {
return llvm_fn;
}
// The function hasn't been registered, let's do it now
llvm::Type *ht_type = CCHashTableProxy::GetType(codegen)->getPointerTo();
llvm::FunctionType *fn_type =
llvm::FunctionType::get(codegen.VoidType(), ht_type);
return codegen.RegisterFunction(fn_name, fn_type);
}
//===----------------------------------------------------------------------===//
// STORE TUPLE PROXY
//===----------------------------------------------------------------------===//
const std::string &CCHashTableProxy::_StoreTuple::GetFunctionName() {
static const std::string kStoreTupleFnName =
#ifdef __APPLE__
"_ZN7peloton7codegen5utils11CCHashTable10StoreTupleEmj";
#else
"_ZN7peloton7codegen5utils11CCHashTable10StoreTupleEmj";
#endif
return kStoreTupleFnName;
}
llvm::Function *CCHashTableProxy::_StoreTuple::GetFunction(CodeGen &codegen) {
const std::string fn_name = GetFunctionName();
// Has the function already been registered?
llvm::Function *llvm_fn = codegen.LookupFunction(fn_name);
if (llvm_fn != nullptr) {
return llvm_fn;
}
// The function hasn't been registered, let's do it now
llvm::Type *ht_type = CCHashTableProxy::GetType(codegen)->getPointerTo();
std::vector<llvm::Type *> parameter_types{ht_type, codegen.Int64Type(),
codegen.Int32Type()};
llvm::FunctionType *fn_type =
llvm::FunctionType::get(codegen.CharPtrType(), parameter_types, false);
return codegen.RegisterFunction(fn_name, fn_type);
}
//===----------------------------------------------------------------------===//
// HASH ENTRY
//===----------------------------------------------------------------------===//
llvm::Type *HashEntryProxy::GetType(CodeGen &codegen) {
static const std::string kHashEntryTypeName = "peloton::CCHashEntry";
// Check if the hash entry is already defined in the module
auto *llvm_type = codegen.LookupTypeByName(kHashEntryTypeName);
if (llvm_type != nullptr) {
return llvm_type;
}
// Define the thing (the first field is the 64-bit hash, the second is the
// next HashEntry* pointer)
auto *hash_entry_type =
llvm::StructType::create(codegen.GetContext(), kHashEntryTypeName);
hash_entry_type->setBody(
{codegen.Int64Type(), hash_entry_type->getPointerTo()},
/*is_packed*/ false);
return hash_entry_type;
}
} // namespace codegen
} // namespace peloton | [
"pavlo@cs.brown.edu"
] | pavlo@cs.brown.edu |
855af90b76f61a8ae60052e59f3ec86dcc04805c | e79e60cbad3a63c308c0d4dd2f1dcf47d1a7c6e9 | /src/Util/Random.cpp | ffd61ff549c3a839f8aeafa94866f1b64d1b80fc | [] | no_license | sfalexrog/cmc-terrain | d50de1918b7816c2e5a1d7c748dfe538c045de62 | d11057eeff577ad0c2af49dff8033786c3c9a2ac | refs/heads/main | 2023-07-15T22:08:09.531727 | 2021-08-21T18:34:27 | 2021-08-21T18:34:27 | 338,887,096 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 692 | cpp | #include "Random.hpp"
#include <chrono>
#include <limits>
namespace rng
{
Xorshift128p::Xorshift128p()
{
auto currentTime = std::chrono::system_clock::now();
auto epochTime = currentTime.time_since_epoch();
currState.a = epochTime.count();
// FIXME: needs more random initial state
currState.b = currState.a + 42;
}
uint64_t Xorshift128p::randRaw()
{
uint64_t t = currState.a;
uint64_t s = currState.b;
currState.a = s;
t ^= t << 23;
t ^= t >> 17;
t ^= s ^ (s >> 26);
currState.b = t;
return t + s;
}
double Xorshift128p::rand01()
{
auto raw = randRaw();
return double(raw) / double(std::numeric_limits<uint64_t>::max());
}
}
| [
"sfalexrog@gmail.com"
] | sfalexrog@gmail.com |
2b89fc51532092f80c3a6853550370877bdacccc | f8573941754a429f481c18b46ad5337d1bb55609 | /PhysX.Net 3.3.1/PhysX.Net-3.3/PhysX.Net-3/Source/ArticulationLink.cpp | 64f449251d27e025305d583b990a9c746fe13a17 | [] | no_license | frbyles/ExcavatorSimulator | 409fa4ad56ba3d786dedfffb5d981db86d89f4f5 | c4be4ea60cd1c62c0d0207af31dfed4a47ef6124 | refs/heads/master | 2021-01-19T11:38:04.166440 | 2015-11-12T17:45:52 | 2015-11-12T17:45:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,457 | cpp | #include "StdAfx.h"
#include "ArticulationLink.h"
#include "Articulation.h"
#include "Scene.h"
#include "Physics.h"
//#include <PxArticulation.h>
ArticulationLink::ArticulationLink(PxArticulationLink* articulationLink, PhysX::Articulation^ owner)
: RigidBody(articulationLink, owner->Scene->Physics)
{
}
ArticulationLink::~ArticulationLink()
{
this->!ArticulationLink();
}
ArticulationLink::!ArticulationLink()
{
}
PhysX::Articulation^ ArticulationLink::Articulation::get()
{
return ObjectTable::GetObject<PhysX::Articulation^>((intptr_t)&this->UnmanagedPointer->getArticulation());
}
PhysX::ArticulationJoint^ ArticulationLink::ArticulationJoint::get()
{
auto j = this->UnmanagedPointer->getInboundJoint();
return ObjectTable::GetObject<PhysX::ArticulationJoint^>((intptr_t)&j);
}
array<PhysX::ArticulationLink^>^ ArticulationLink::Children::get()
{
int n = this->UnmanagedPointer->getNbChildren();
auto l = gcnew array<ArticulationLink^>(n);
PxArticulationLink** links = new PxArticulationLink*[n];
int q = this->UnmanagedPointer->getChildren(links, n);
assert(q<=n);
for (int i = 0; i < q; i++)
{
PxArticulation& a = links[i]->getArticulation();
auto articulation = ObjectTable::GetObject<PhysX::Articulation^>((intptr_t)&a);
l[i] = gcnew ArticulationLink(links[i], articulation);
}
return l;
}
PxArticulationLink* ArticulationLink::UnmanagedPointer::get()
{
return (PxArticulationLink*)RigidBody::UnmanagedPointer;
} | [
"seifes1@gmail.com"
] | seifes1@gmail.com |
5a00ce37eae7703621ead3e3ff25327a70440ac9 | bb0fcccf60fa9e0ffc2c36a2a381e5812b43dc08 | /LEETCODE/INTERVIEW/136.cpp | e6273e4aaf7e8f18bcb5f7d7eda1791c70f7a4cf | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | PraneshASP/COMPETITVE-PROGRAMMING | eec52f14f1a77892b4dac5a35d1bda731de0faa3 | 2fb68734146ef64f5c6eb6cf3e8191e362301d75 | refs/heads/master | 2022-12-21T15:29:04.443467 | 2020-10-01T05:45:47 | 2020-10-01T05:45:47 | 298,556,530 | 0 | 0 | NOASSERTION | 2020-09-25T11:43:12 | 2020-09-25T11:43:11 | null | UTF-8 | C++ | false | false | 1,259 | cpp | /*
136. Single Number
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
*/
#include <bits/stdc++.h>
using namespace std;
int singleNumber(vector<int> &nums)
{
// using hashmap will take O(n) space
map<int, int> m;
for (int i = 0; i < nums.size(); i++)
{
auto itr = m.find(nums[i]);
if (itr != m.end())
itr->second++;
else
m.insert(make_pair(nums[i], 1));
}
for (auto itr = m.begin(); itr != m.end();)
{
if (itr->second == 1)
return itr->first;
}
}
int solution2(vector<int> &nums)
{
/*
Concept
If we take XOR of zero and some bit, it will return that bit
If we take XOR of two same bits, it will return 0
So we can XOR all bits together to find the unique number.
*/
int a = 0;
for (int i = 0; i < nums.size(); i++)
a ^= nums[i];
return a;
}
int main()
{
vector<int> nums({2, 2, 1});
cout << singleNumber(nums) << endl << solution2(nums) << endl;
return 0;
} | [
"duhan.sachin2610@gmail.com"
] | duhan.sachin2610@gmail.com |
9255221f3bc9e73c9b71e36d9fbde7bf42aca5a9 | 208c9c4fc8d8ad06f1ca56a0a68470927534c190 | /Hello.cpp | 5b2f5662b0751da3d700506a1927f671e219a178 | [] | no_license | Tenderest/CPP-Learning | e367adf5c0abb497992c0d4f5c8ce2289db0faf9 | 7fc92c96b00f9ecf8c27f68039a6fea4bb1fbb8d | refs/heads/main | 2022-10-15T19:36:29.384763 | 2022-05-27T08:55:27 | 2022-05-27T08:55:27 | 233,337,137 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 139 | cpp | #include <iostream>
int main(void)
{
// using namespace std;
std::cout << "Hello World!" << std::endl;
return 0;
}
| [
"2087886585@qq.com"
] | 2087886585@qq.com |
b800afd3b17005459a70168690c1883d90ff5ebc | 0c51500f87101f13c471f0c310e9451a87adc714 | /flammap/win32/burnupw.cpp | ab23a6c27cefaeaaf306669edeed152270a7decc | [
"LicenseRef-scancode-public-domain",
"Unlicense"
] | permissive | firelab/wfips | a5e589fde41579e87008a7900a87692ec985e529 | 6b3bd4934d281ebb31164bd242a57079a82053b0 | refs/heads/master | 2020-05-01T06:03:41.792664 | 2017-01-27T19:31:55 | 2017-01-27T19:31:55 | 14,540,320 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 65,942 | cpp | //------------------------------------------------------------------------------
// Burnup, Albini and Reinhardt
//
//
//------------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <windows.h>
#include "burnupcw.h"
//#include "nonlin.h"
static const double ch2o=4186.0;
static const double tpdry=353.0;
static const double smallx=1.e-06;
static const double big= 1.e+06;
#define min(a,b) ((a<b) ? a : b)
#define max(a,b) ((a>b) ? a : b)
double BurnUp::pow2(double input)
{
return input*input;
}
void BurnUp::ResetEmissionsData()
{
long i;
for(i=0; i<MAXNO; i++)
{ Smoldering[i]=0.0;
Flaming[i]=0.0;
}
Smoldering[MAXNO]=0.0;
}
BurnUp::BurnUp()
{
long i;
ntimes=0;
number=0;
fi =0.0;
ti =0.0;
u =0.0;
d =0.0;
tamb =0.0;
ak =0.0;
r0 =0.0;
dr =0.0;
dt =0.0;
wdf =0.0;
dfm =2.0;
for(i=0; i<MAXNO; i++)
{ wdry[i] =0.0;
ash[i] =0.0;
htval[i] =0.0;
fmois[i] =0.0;
dendry[i] =0.0;
sigma[i] =0.0;
cheat[i] =0.0;
condry[i] =0.0;
alfa[i] =0.0;
tpig[i] =0.0;
tchar[i] =0.0;
flit[i] =0.0;
fout[i] =0.0;
work[i] =0.0;
alone[i] =0.0;
area[i] =0.0;
fint[i] =0.0;
Smoldering[i]=0.0;
Flaming[i]=0.0;
}
Smoldering[MAXNO]=0.0;
//memset(Message, 0x0, sizeof(Message));
ZeroMemory(Message, sizeof(Message));
fistart=-1.0;
NumAllocRegrData=0;
x=y=w=0; // arrays for regression
ux=vx=0;
sig=0;
FintSwitch=15.0;
bs=0;
}
BurnUp::~BurnUp()
{
FreeBurnStruct();
FreeRegressionData(NumAllocRegrData);
}
bool BurnUp::CheckData()
{
long i;
const double ash1=0.0001, ash2=0.1;
const double htv1=1.0e07, htv2=3.0e7;
const double fms1=0.01, fms2=3.0;
const double den1=200.0, den2=1000.0;
const double sig1=4.0, sig2=1.0e4;
const double cht1=1000.0, cht2=4000.0;
const double con1=0.025, con2=0.25;
const double tig1=200.0, tig2=400.0;
const double tch1=250.0, tch2=500.0;
const double fir1=0.1, fir2=1.0e5;
const double ti1=1.0, ti2=200.0;
const double u1=0.0, u2=5.0;
const double d1=0.1, d2=5.0;
const double tam1=-40.0, tam2=40.0;
const double wdf1=0.1, wdf2=30.0;
const double dfm1=0.1, dfm2=1.972;
for(i=0; i<number; i++)
{ sprintf(Message, "%s %ld", "Line Number", i);
if(wdry[i]<=smallx || wdry[i]>=big)
{ strcat(Message, " dry loading out of range (kg/m2)");
break;
}
if(ash[i]<=ash1 || ash[i]>=ash2)
{ strcat(Message, " ash content out of range (fraction)");
break;
}
if(htval[i]<=htv1 || htval[i]>=htv2)
{ strcat(Message, " heat content out of range (J/kg)");
break;
}
if(fmois[i]<=fms1 || fmois[i]>=fms2)
{ strcat(Message, " fuel moisture out of range (fraction)");
break;
}
if(dendry[i]<=den1 || dendry[i]>=den2)
{ strcat(Message, " dry mass density out of range (kg/m3)");
break;
}
if(sigma[i]<=sig1 || sigma[i]>=sig2)
{ strcat(Message, " SAV out of range (1/m)");
break;
}
if(cheat[i]<=cht1 || cheat[i]>=cht2)
{ strcat(Message, " heat capacity out of range (J/kg/K");
break;
}
if(condry[i]<=con1 || condry[i]>=con2)
{ strcat(Message, " thermal conductivity out of range (W/m/K)");
break;
}
if(tpig[i]<=tig1 || tpig[i]>=tig2)
{ strcat(Message, " ignition temperature out of range (C)");
break;
}
if(tchar[i]<=tch1 || tchar[i]>=tch2)
{ strcat(Message, " char end pyrolisis temperature out of range (C)");
break;
}
}
if(i<number)
return false;
//memset(Message, 0x0, sizeof(Message));
ZeroMemory(Message, sizeof(Message));
if(ti<ti1)
{ double rat, tempf, tempt;
rat=fistart/ti;
tempf=fir1;
tempt=(fistart-fir1)/rat;
ti+=tempt;
fistart=tempf;
}
if(fistart<fir1 || fistart>fir2)
strcat(Message, " igniting fire intensity out of range (kW/m2)");
else if(ti<ti1)// || ti>ti2 )
strcat(Message, " igniting surface fire res. time out of range (s)");
else if(u<u1 || u>u2)
strcat(Message, " windspeed at top of fuelbed out of range (m/s)");
else if(d<d1 || d>d2)
strcat(Message, " depth of fuel bed out of range (m)");
else if(tamb-273<tam1 || tamb-273>tam2)
strcat(Message, " ambient temperature out of range (C)");
//else if(wdf<wdf1 || wdf>wdf2)
// strcat(Message, " duff dry weight loading out of range (kg/m2)");
else if(dfm<dfm1 || dfm>dfm2)
strcat(Message, " duff moisture out of range (fraction)");
if(strlen(Message)>0)
return false;
AllocBurnStruct(); // allocate for ntimes of output data
return true;
}
bool BurnUp::GetDatFile(char *InFile, long Number)
{
long i;
double drywt, ashes, hots, fms, dryd, sigs, cpd, cond, tigi, tchi;
FILE *infile;
number=Number; // class copy of Number of fuel classes
if(number>MAXNO)
return false;
if((infile=fopen(InFile, "r"))==NULL)
return false;
for(i=0; i<number; i++)
{ fscanf(infile, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf",
&drywt, &ashes, &hots, &fms, &dryd, &sigs, &cpd, &cond, &tigi, &tchi);
wdry[i]=drywt;
ash[i]=ashes;
htval[i]=hots;
fmois[i]=fms;
dendry[i]=dryd;
sigma[i]=sigs;
cheat[i]=cpd;
condry[i]=cond;
tpig[i]=tigi+273.0;
tchar[i]=tchi+273.0;
}
fscanf(infile, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %ld %lf %lf",
&fi, &ti, &u, &d, &tamb, &ak, &r0, &dr, &dt, &ntimes, &wdf, &dfm);
tamb+=273;
fclose(infile);
if(!CheckData())
return false;
return true;
}
bool BurnUp::SetFuelStruct(long NumParts, FuelStruct *fs)
{
long i;
number=NumParts;
if(number>MAXNO)
{ sprintf(Message, "%s %ld", "Number of fuel partitions exceeds max:", MAXNO);
return false;
}
for(i=0; i<number; i++)
{ wdry[i]=fs[i].wdry;
ash[i]=fs[i].ash;
htval[i]=fs[i].htval*1000.0;
fmois[i]=fs[i].fmois;
dendry[i]=fs[i].dendry;
sigma[i]=fs[i].sigma;
cheat[i]=fs[i].cheat;
condry[i]=fs[i].condry;
tpig[i]=fs[i].tpig+273.0;
tchar[i]=fs[i].tchar+273.0;
}
return true;
}
bool BurnUp::SetFuelDat(long NumParts, double *drywt, double *ashes, double *hots,
double *fms, double *dryd, double *sigs,
double *cpd, double *cond, double *tigi,
double *tchi)
{
long i;
number=NumParts;
if(number>MAXNO)
{ sprintf(Message, "%s %ld", "Number of fuel partitions exceeds max:", MAXNO);
return false;
}
for(i=0; i<number; i++)
{ wdry[i]=drywt[i];
ash[i]=ashes[i];
htval[i]=hots[i];
fmois[i]=fms[i];
dendry[i]=dryd[i];
sigma[i]=sigs[i];
cheat[i]=cpd[i];
condry[i]=cond[i];
tpig[i]=tigi[i]+273.0;
tchar[i]=tchi[i]+273.0;
}
return true;
}
bool BurnUp::SetFuelInfo(long NumParts, double *datastruct)
{
long i;
number=NumParts;
if(number>MAXNO)
{ sprintf(Message, "%s %ld", "Number of fuel partitions exceeds max:", MAXNO);
return false;
}
for(i=0; i<number; i++)
{ sigma[i]=datastruct[i*5];
wdry[i]=datastruct[i*5+1];
htval[i]=datastruct[i*5+2]*1000.0;
dendry[i]=datastruct[i*5+3];
fmois[i]=datastruct[i*5+4];
ash[i]= 0.05;
cheat[i]= 2750.0;
condry[i]=0.133;
tpig[i]= 327;// deg C+273;
tchar[i]= 377;// deg C+273;
}
return true;
}
bool BurnUp::SetFireDat(long NumIter, double Fi, double Ti, double U, double D, double Tamb,
double R0, double Dr, double Dt, double Wdf, double Dfm)
{
ntimes=NumIter;
if(ntimes<=0)
{ sprintf(Message, "%s", "Number of Iterations too smallx (<=0");
return false;
}
fistart=Fi;
ti=Ti;
u=U;
d=D;
tamb=Tamb+273.0;
r0=R0;
dr=Dr;
dt=Dt;
wdf=Wdf;
dfm=Dfm;
return true;
}
bool BurnUp::Burnup()
{
char HistFile[]="burn_hist.txt";
char SnapFile[]="burn_snap.txt";
long nruns = 0;
long now, nohist=0;
double fimin = 0.1;
double tis, dfi, tdf, fid;
if(ntimes==0 || number==0)
return false;
ResetEmissionsData();
fi=fistart;
Arrays();
now=1;
tis=ti;
DuffBurn(wdf, dfm, &dfi, &tdf);
Start(tis, now, &nruns);
if(tis<tdf)
fid=dfi;
else
fid=0.0;
if(!nohist)
Stash(HistFile, SnapFile, tis, now);
fi=FireIntensity();
if(fi>fimin)
{ do
{ Step(dt, tis, fid, &nruns);
now++;
tis+=dt;
if(tis<tdf)
fid=dfi;
else
fid=0.0;
fi=FireIntensity();
if(fi<=fimin)
break;
if(!nohist)
Stash(HistFile, SnapFile, tis, now);
} while(now<=ntimes);
}
Summary(HistFile);
return true;
}
bool BurnUp::StartLoop()
{
fimin = 0.1;
fi=fistart;
if(ntimes==0 || number==0)
return false;
ResetEmissionsData();
Arrays();
now=1;
tis=ti;
DuffBurn(wdf, dfm, &dfi, &tdf);
if(Start(tis, now, &nruns))
{ if(tis<tdf)
fid=dfi;
else
fid=0.0;
SetBurnStruct(0.0, now);
fi=FireIntensity();
SetBurnStruct(tis, now);
nruns=0;
if(fi<=fimin)
return false;
}
else
return false;
return true;
}
bool BurnUp::BurnLoop()
{
Step(dt, tis, fid, &nruns);
now++;
tis+=dt;
if(tis<tdf)
fid=dfi;
else
fid=0.0;
fi=FireIntensity();
if(fi<=fimin)
{ fi=fistart;
while(tis<tdf && now<ntimes)
{ fi=fid;
SetBurnStruct(tis, now++);
tis+=dt;
};
return false;
}
SetBurnStruct(tis, now);
if(now>ntimes)
return false;
return true;
}
long BurnUp::loc(long k, long l)
{
return k*(k+1.0)/2.0+l-1;
//return k*((long) ((k+1)/2))+l-1;
/*
double HalfK;
HalfK=(double) (k+1.0)/2.0;
return (long) ((double) k*HalfK+l)-1;
*/
}
long BurnUp::Nint(double input)
{
long Input;
Input=(long) input;
if(input-(double) Input>=0.5)
Input+=1;
return Input;
}
//------------------------------------------------------------------------------
//
// Tignit
//
//------------------------------------------------------------------------------
// subroutine TIGNIT( tpam , tpdr , tpig , tpfi , cond ,
// + chtd , fmof , dend , hbar , tmig )
//c tpam = ambient temperature , K
//c tpdr = fuel temperature at start of drying , K
//c tpig = fuel surface temperature at ignition , K
//c tpfi = fire environment temperature , K
//c cond = fuel ovendry thermal conductivity , W / m K
//c chtd = fuel ovendry specific heat capacity , J / kg K
//c fmof = fuel moisture content , fraction dry weight
//c dend = fuel ovendry density , kg / cu m
//c hbar = effective film heat transfer coefficient [< HEATX] W / sq m K
//c tmig = predicted time to piloted ignition , s
double BurnUp::ff(double x, double tpfi, double tpig)
{
const double a03=-1.3371565;
const double a13=0.4653628;
const double a23=-0.1282064;
double b03;
b03=a03*(tpfi-tpig)/(tpfi-tamb);
return b03+x*(a13+x*(a23+x));
}
double BurnUp::TIgnite(double tpdr, double tpig, double tpfi,
double cond, double chtd, double fmof, double dend,
double hbar)
{
const double pinv=2.125534;
const double hvap=2.177e+06;
const double cpm=4186.0;
const double conc=4.27e-04;
double xlo, xhi, xav, fav, beta, conw, dtb, dti, ratio, rhoc, tmig;
// MOVED TO function FF(...)
//------------------------------------------------------------------------------
//c approximate function of beta to be solved is ff( x ) where
//c x = 1 / ( 1 + p * beta ) { Hastings, Approximations for
//c digital computers } and we employ pinv = 1 / p
// ff( x ) = b03 + x * ( a13 + x * ( a23 + x ) )
//c radiant heating equivalent form gives end condition fixes beta
// b03 = a03 * ( tpfi - tpig ) / ( tpfi - tpam )
//------------------------------------------------------------------------------
//c find x that solves ff( x ) = 0 ; method is binary search
xlo = 0.0;
xhi = 1.0;
do
{ xav = 0.5 * ( xlo + xhi );
fav = ff(xav, tpfi, tpig);
if(fabs(fav)>smallx)
{ if(fav<0.0)
xlo = xav;
if(fav>0.0)
xhi = xav;
}
} while(fabs(fav)>smallx);
beta = pinv*(1.0-xav)/xav;
conw = cond+conc*dend*fmof;
dtb = tpdr-tamb;
dti = tpig-tamb;
ratio = (hvap+cpm*dtb)/(chtd*dti);
rhoc = dend*chtd*(1.0+fmof*ratio);
tmig = pow2(beta/hbar)*conw*rhoc;
return tmig;
}
//------------------------------------------------------------------------------
//
// DuffBurn
//
//------------------------------------------------------------------------------
void BurnUp::DuffBurn(double wdf, double dfm, double *dfi, double *tdf)
{
//c Duff burning rate (ergo, intensity) and duration
double ff;
*dfi = 0.0;
*tdf = 0.0;
if((wdf<=0.0) || (dfm >=1.96))
return;
*dfi=11.25-4.05*dfm;
ff=0.837-0.426*dfm;
*tdf=1.e+04*ff*wdf/(7.5-2.7*dfm);
Smoldering[MAXNO]+=((ff*wdf)/(*tdf));
}
//------------------------------------------------------------------------------
//
// Arrays
//
//------------------------------------------------------------------------------
void BurnUp::Arrays()
{
// subroutine ARRAYS( maxno , number , wdry , ash , dendry , fmois ,
// + sigma , htval , cheat , condry , tpig , tchar ,
// + diam , key , work , ak , elam , alone , xmat ,
// + wo , maxkl )
//c Orders the fuel description arrays according to the paradigm described in
//c subroutine SORTER and computes the interaction matrix xmat from the array
//c elam and the list alone returned from subroutine OVLAPS. Parameters in
//c arrays are defined in terms of initial values as:
//c wdry ovendry mass loading , kg / sq m
//c ash mineral content , fraction dry mass
//c dendry ovendry mass density , kg / cu m
//c fmois moisture content , fraction dry mass
//c sigma surface to volume ratio , 1 / m
//c htval low heat of combustion , J / kg
//c cheat specific heat capacity , ( J / K ) / kg dry mass
//c condry thermal conductivity , W / m K , ovendry
//c tpig ignition temperature , K
//c tchar char temperature , K
//c diam initial diameter , m [ by interaction pairs ]
//c key ordered index list
//c work workspace array
//c elam interaction matrix from OVLAPS
//c alone noninteraction fraction list from OVLAPS
//c xmat consolidated interaction matrix
//c wo initial dry loading by interaction pairs
// real*4 wdry( maxno ) , ash( maxno ) , dendry( maxno )
// real*4 fmois( maxno ) , sigma( maxno ) , htval( maxno )
// real*4 cheat( maxno ) , condry( maxno ) , tpig( maxno )
// real*4 tchar( maxno ) , work( maxno )
// real*4 elam( maxno , maxno ) , alone( maxno )
// real*4 xmat( maxkl ) , diam( maxkl ) , wo( maxkl )
// integer key( maxno )
double diak, wtk;
long j, k, kl, kj;
Sorter(); // call SORTER( maxno , number , sigma , fmois , dendry , key )
for(j=0; j<number; j++)
{ k = key[j];
work[j]= wdry[k];
}
for(j=0; j<number; j++)
wdry[j] = work[j];
for(j=0; j<number; j++)
{ k = key[j];
work[j]= ash[k];
}
for(j=0; j<number; j++)
ash[j] = work[j];
for(j=0; j<number; j++)
{ k = key[j];
work[j]= htval[k];
}
for(j=0; j<number; j++)
htval[j]= work[j];
for(j=0; j<number; j++)
{ k = key[j];
work[j]= cheat[k];
}
for(j=0; j<number; j++)
cheat[j] = work[j];
for(j=0; j<number; j++)
{ k = key[j];
work[j]= condry[k];
}
for(j=0; j<number; j++)
condry[j] = work[j];
for(j=0; j<number; j++)
{ k = key[j];
work[j]= tpig[k];
}
for(j=0; j<number; j++)
tpig[j] = work[j];
for(j=0; j<number; j++)
{ k = key[j];
work[j]= tchar[k];
}
for(j=0; j<number; j++)
tchar[j] = work[j];
OverLaps(); // call OVLAPS( wdry , sigma , dendry , ak , number , maxno , maxkl , xmat , elam , alone )
for(k=1; k<=number; k++) //do k = 1 , number
{ diak = 4.0/sigma[k-1];
wtk = wdry[k-1];
kl = loc(k, 0);
diam[kl] = diak;
xmat[kl] = alone[k-1];
wo[kl] = wtk * xmat[kl];
for(j=1; j<=k; j++) //do j = 1 , k
{ kj = loc(k, j);
diam[kj] = diak;
xmat[kj] = elam[k-1][j-1];
wo[kj] = wtk * xmat[kj];
}
}
}
//------------------------------------------------------------------------------
//
// TempF
//
//------------------------------------------------------------------------------
double BurnUp::TempF(double q, double r)
{
// function TEMPF( q , r , tamb )
//c Returns a fire environment temperature , TEMPF , given the fire intensity
//c q in kW / square meter , the ambient temperature tamb in Kelvins, and the
//c dimensionless mixing parameter r.
const double err=1.0e-04;
const double aa=20.0;
double term, rlast, den, rnext, test, tempf;
term=r/(aa*q);
rlast=r;
do
{ den=1.0+term*(rlast+1.0)*(rlast*rlast+1.0);
rnext=0.5*(rlast+1.0+r/den);
test=fabs(rnext-rlast);
if(test<err)
{ tempf=rnext*tamb;
break;
}
rlast=rnext;
} while(test>=err);
return tempf;
}
//----------------------------------------------------------------------------
//
// Step
//
//----------------------------------------------------------------------------
/*
subroutine STEP( dt , MXSTEP , now , maxno , number , wo , alfa ,
+ dendry , fmois , cheat , condry , diam , tpig ,
+ tchar , xmat , tambb , tpdry , fi , flit , fout ,
+ tdry , tign , tout , qcum , tcum , acum , qdot ,
+ ddot , wodot , work , u , d , r0 , dr , ch2o ,
+ ncalls , maxkl , tin , fint , fid )
c Updates status of all fuel component pairs and returns a snapshot
c
c Input parameters:
c
c tin = start of current time step
c dt = time step , sec
c MXSTEP = max dimension of historical sequences
c now = index marks end of time step
c maxno = max number of fuel components
c number = actual number of fuel components
c wo = current ovendry loading for the larger of
c each component pair, kg / sq m
c alfa = dry thermal diffusivity of component , sq m / s
c dendry = ovendry density of component , kg / cu m
c fmois = moisture fraction of component
c cheat = specific heat capacity of component , J / kg K
c condry = ovendry thermal conductivity , w / sq m K
c diam = current diameter of the larger of each
c fuel component pair , m
c tpig = ignition temperature ( K ) , by component
c tchar = end - pyrolysis temperature ( K ) , by component
c xmat = table of influence fractions between components
c tambb = ambient temperature ( K )
c tpdry = temperature ( all components ) start drying ( K )
c fi = current fire intensity ( site avg ) , kW / sq m
c work( k ) = factor of heat transfer rate hbar * (Tfire - Tchar)
c that yields ddot( k )
c fint( k ) = correction to fi to compute local intensity
c that may be different due to k burning
c fid = fire intensity due to duff burning ... this is
c used to up the fire intensity for fuel pieces
c that are burning without interacting with others
c plus the following constants and bookkeeping parameters
c u , d , r0 , dr , ch20 , ncalls , maxkl
c
c Parameters updated [input and output]
c
c ncalls = counter of calls to this routine ...
c = 0 on first call or reset
c cumulates after first call
c flit = fraction of each component currently alight
c fout = fraction of each component currently gone out
c tdry = time of drying start of the larger of each
c fuel component pair
c tign = ignition time for the larger of each
c fuel component pair
c tout = burnout time of larger component of pairs
c qcum = cumulative heat input to larger of pair , J / sq m
c tcum = cumulative temp integral for qcum ( drying )
c acum = heat pulse area for historical rate averaging
c qdot = history ( post ignite ) of heat transfer rate
c to the larger of component pair , W / sq m
c ddot = diameter reduction rate , larger of pair , m / s
c wodot = dry loading loss rate for larger of pair
c
c Constant parameters
c
c u = mean horizontal windspeed at top of fuelbed
c d = fuelbed depth
c r0 = minimum value of mixing parameter
c dr = max - min value of mixing parameter
c ch2o = specific heat capacity of water , J / kg K
c hvap = heat of vaporization of water , J / kg
*/
//real*4 wo( maxkl ) , alfa( maxno ) , dendry( maxno )
//real*4 fmois( maxno ) , cheat( maxno )
//real*4 condry( maxno ) , diam( maxkl ) , tpig( maxno )
//real*4 tchar( maxno ) , xmat( maxkl )
//real*4 tdry( maxkl ) , tign( maxkl )
//real*4 tout( maxkl ) , qcum( maxkl )
//real*4 tcum( maxkl ) , acum( maxkl )
//real*4 qdot( maxkl , MXSTEP ) , ddot( maxkl )
//real*4 wodot( maxkl ) , flit( maxno ) , fout( maxno )
//real*4 work( maxno ) , fint( maxno )
void BurnUp::Step(double dt, double tin, double fid, long *ncalls)
{
int nspan;
long k, l, j, kl, next, now, mu, index;
double c, rindef=1.e+30;
double tnext, tnow, tgo, tdun, tifi;
double aint, tav1, tav2, tav3, tavg;
double qdavg, qdsum, tspan, deltim;
double tlit, ts, r, gi, tf, dia, hf, hb;
double e, qqq, tst, dnext, wnext, rate, ddt, dryt, dtemp, dqdt;
double dteff, heff, tfe, dtlite, qd, delt, factor;
double conwet, dtcum, he, dtef, thd, biot, cpwet, tbar, fac;
bool flag;
*ncalls+=1;
now=*ncalls;
tnow = tin;
tnext = tnow + dt;
//c tifi = time when fire ignition phase ended ( at now = 1 )
tifi = tnow-((double)(now-1))*dt;
next = now+1;
for(k=1; k<=number; k++) //do k = 1 , number
{ c = condry[k-1];
for(l=0; l<=k; l++) //do l = 0 , k
{ kl = loc(k, l);
tdun = tout[kl];
//c See if k of ( k , l ) pair burned out
if(tnow>=tdun)
{ ddot[kl]=0.0;
wodot[kl]=0.0;
continue; // goto 10
}
if(tnext>=tdun)
{ tgo = tdun-tnow;
ddot[kl] = diam[kl]/tgo;
wodot[kl] = wo[kl]/tgo;
wo[kl] = 0.0;
diam[kl]= 0.0;
continue;
}
//c k has not yet burned out ... see if k of ( k , l ) pair is ignited
tlit = tign[kl];
if(tnow>=tlit)
{ ts = tchar[k-1];
if(l==0)
{ r = r0 + 0.5 * dr;
gi = fi + fid;
}
else if(l==k)
{ r =r0+0.5*(1.0+flit[k-1])*dr;
gi =fi+flit[k-1]*fint[k-1];
}
else//(l!=0 && l!=k)
{ r = r0+0.5*(1.0+flit[l-1])*dr;
gi =fi+fint[k-1]+flit[l-1]*fint[l-1];
}
tf = TempF(gi, r);
dia = diam[kl];
HeatExchange(dia, tf, ts, &hf, &hb, c, &e);
qqq = hb * max(tf-ts, 0.0);
tst = max(tlit, tifi);
nspan = max((long) 1, Nint((tnext-tst)/dt)); //nint((tnext-tst)/dt));
if(nspan<=MXSTEP)
qdot[kl][nspan-1]=qqq;
else if(nspan>MXSTEP)
{ for(mu=2; mu<=MXSTEP; mu++) //do mu = 2 , MXSTEP
qdot[kl][mu-2]=qdot[kl][mu-1];
qdot[kl][MXSTEP-1]=qqq;
}
aint = pow2(c/hb);
acum[kl]+=(aint*dt);
tav1 = tnext-tlit;
tav2 = acum[kl]/alfa[k-1];
tav3 = pow2(dia/4.0)/alfa[k-1];
tavg=tav1;
if(tav2<tavg)
tavg=tav2;
if(tav3<tavg)
tavg=tav3;
index=min(nspan, MXSTEP); //index = 1+min(nspan, MXSTEP);
qdsum=0.0;
tspan=0.0;
deltim=dt;
do
{ index-=1;
if(index==0) //==1
deltim=tnext-tspan-tlit;
if((tspan+deltim)>=tavg)
deltim=tavg-tspan;
qdsum+=(qdot[kl][index]*deltim);
tspan+=deltim;
if(tspan>=tavg)
break;
} while(index>0);
qdavg = max(qdsum/tspan, 0.0);
ddot[kl] =qdavg*work[k-1];
dnext = max(0.0, dia-dt*ddot[kl]);
wnext = wo[kl]*pow2(dnext/dia);
if((dnext==0.0) && (ddot[kl]>0.0))
tout[kl]=tnow+dia/ddot[kl];
else if((dnext>0.0) && (dnext<dia))
{ rate=dia/(dia-dnext);
tout[kl]=tnow+rate*dt;
}
if(qdavg<=(double) MXSTEP) // <=20.0 in Albini's code
tout[kl]=0.5*(tnow+tnext);
ddt = min(dt, (tout[kl]-tnow));
wodot[kl]=(wo[kl]-wnext)/ddt;
diam[kl]=dnext;
wo[kl]=wnext;
continue; //goto 10
}
//c See if k of ( k , l ) has reached outer surface drying stage yet
dryt = tdry[kl];
if(tnow>=dryt && tnow<tlit)
{ if(l==0)
{ r=r0;
gi=fi+fid;
}
else if(l==k)
{ r=r0;
gi=fi;
}
else// if(l!=0 && l!=k)
{ r=r0+0.5*flit[l-1]*dr;
gi=fi+flit[l-1]*fint[l-1];
}
tf = TempF(gi, r);
ts = tamb;
dia = diam[kl];
HeatExchange(dia, tf, ts, &hf, &hb, c, &e);
//call heatx( u , d , dia , tf , ts , hf , hb , c , e )
dtemp=max(0.0, tf-ts);
dqdt=hb*dtemp;
qcum[kl]+=(dqdt*dt);
tcum[kl]+=(dtemp*dt);
dteff=tcum[kl]/(tnext-dryt);
heff=qcum[kl]/tcum[kl];
tfe=ts+dteff;
dtlite=rindef;
if(tfe>(tpig[k-1]+10.0))
dtlite=TIgnite(tpdry, tpig[k-1], tfe,
condry[k-1], cheat[k-1], fmois[k-1], dendry[k-1], heff);
tign[kl]=0.5*(dryt+dtlite);
//c If k will ignite before time step over , must interpolate
if(tnext>tign[kl])
{ ts = tchar[k-1];
HeatExchange(dia, tf, ts, &hf, &hb, c, &e);
qdot[kl][0]=hb*max(tf-ts, 0.0);
qd=qdot[kl][0];
ddot[kl]=qd*work[k-1];
delt=tnext-tign[kl];
dnext=max(0.0, dia-delt*ddot[kl]);
wnext=wo[kl]*pow2(dnext/dia);
if(dnext==0.0)
tout[kl]=tnow+dia/ddot[kl];
else if((dnext>0.0) && dnext<dia)
{ rate=dia/(dia-dnext);
tout[kl]=tnow+rate*dt;
}
if(tout[kl]>tnow)
{ ddt=min(dt, (tout[kl]-tnow));
wodot[kl]=(wo[kl]-wnext)/ddt;
}
else
wodot[kl]=0.0;
diam[kl]=dnext;
wo[kl]=wnext;
}
continue; // goto 10
}
//c If k of ( k , l ) still coming up to drying temperature , accumulate
//c heat input and driving temperature difference , predict drying start
if(tnow<dryt)
{ factor=fmois[k-1]*dendry[k-1];
conwet=condry[k-1]+4.27e-04*factor;
if(l==0)
{ r=r0;
gi=fi+fid;
}
else if(l==k)
{ r=r0;
gi=fi;
}
else if((l!=0) && (l!=k))
{ r=r0+0.5*flit[l-1]*dr;
gi=fi+flit[l-1]*fint[l-1];
}
tf = TempF(gi, r);
if(tf<=(tpdry+10.0))
continue; // goto 10
dia=diam[kl];
ts=0.5*(tamb+tpdry);
HeatExchange(dia, tf, ts, &hf, &hb, c, &e);
dtcum = max((tf-ts)*dt, 0.0);
tcum[kl]+=dtcum;
qcum[kl]+=(hb*dtcum);
he=qcum[kl]/tcum[kl];
dtef=tcum[kl]/tnext;
thd=(tpdry-tamb)/dtef;
if(thd>0.9)
continue;
biot=he*dia/conwet;
dryt=DryTime(biot, thd);
cpwet=cheat[k-1]+ch2o*fmois[k-1];
fac=pow2(0.5*dia)/conwet;
fac=fac*cpwet*dendry[k-1];
tdry[kl]=fac*dryt;
if(tdry[kl]<tnext)
{ ts=tpdry;
HeatExchange(dia, tf, ts, &hf, &hb, c, &e);
dqdt=hb*(tf-ts);
delt=tnext-tdry[kl];
qcum[kl]=dqdt*delt;
tcum[kl]=(tf-ts)*delt;
tbar=0.5*(tpdry+tpig[k-1]);
//c See if ignition to occur before time step complete
if(tf<=(tpig[k-1]+10.0))
continue;
dtlite=TIgnite(tpdry, tpig[k-1], tf, condry[k-1],
cheat[k-1] , fmois[k-1] , dendry[k-1], hb);
tign[kl]=0.5*(tdry[kl]+dtlite);
if(tnext>tign[kl])
{ ts=tchar[k-1];
qdot[kl][0]=hb*max(tf-ts, 0.0);
}
}
}
}
}
//c Update fractions ignited and burned out , to apply at next step start
for(k=1; k<=number; k++) // do k = 1 , number
{ flit[k-1]=0.0;
fout[k-1]=0.0;
for(l=0; l<=k; l++) //do l = 0 , k
{ kl=loc(k, l);
if(tnext>=tign[kl])
flag=true;
else
flag=false;
if(flag && tnext<=tout[kl])
flit[k-1]+=xmat[kl];
if(tnext>tout[kl])
fout[k-1]+=xmat[kl];
}
}
}
//------------------------------------------------------------------------------
//
// Start
//
//------------------------------------------------------------------------------
// subroutine START( dt , MXSTEP , now , maxno , number , wo , alfa ,
// + dendry , fmois , cheat , condry , diam , tpig ,
// + tchar , xmat , tambb , tpdry , fi , flit , fout ,
// + tdry , tign , tout , qcum , tcum , acum , qdot ,
// + ddot , wodot , work , u , d , r0 , dr , ch2o ,
// + ncalls , maxkl )
//c This routine initializes variables prior to starting sequence of calls
//c to subroutine STEP. On input here, fi is area intensity of spreading
//c fire , dt is the residence time for the spreading fire. Only physical
//c parameters specified are the fuel array descriptors. To call STEP ,
//c one must initialize the following variables.
//c
//c Input parameters:
//c
//c dt = spreading fire residence time , sec
//c MXSTEP = max dimension of historical sequences
//c now = index marks end of time step
//c maxno = max number of fuel components
//c number = actual number of fuel components
//c wo = current ovendry loading for the larger of
//c each component pair, kg / sq m
//c alfa = dry thermal diffusivity of component , sq m / s
//c dendry = ovendry density of component , kg / cu m
//c fmois = moisture fraction of component
//c cheat = specific heat capacity of component , J / kg K
//c condry = ovendry thermal conductivity , W / sq m K
//c diam = current diameter of the larger of each
//c fuel component pair , m
//c tpig = ignition temperature ( K ) , by component
//c tchar = end - pyrolysis temperature ( K ) , by component
//c xmat = table of influence fractions between components
//c tambb = ambient temperature ( K )
//c fi = current fire intensity ( site avg ) , kW / sq m
//c
//c Parameters updated [input and output]
//c
//c ncalls = counter of calls to this routine ...
//c = 0 on first call or reset
//c cumulates after first call
//c flit = fraction of each component currently alight
//c fout = fraction of each component currently gone out
//c tdry = time of drying start of the larger of each
//c fuel component pair
//c tign = ignition time for the larger of each
//c fuel component pair
//c tout = burnout time of larger component of pairs
//c qcum = cumulative heat input to larger of pair , J / sq m
//c tcum = cumulative temp integral for qcum ( drying )
//c acum = heat pulse area for historical rate averaging
//c qdot = history ( post ignite ) of heat transfer rate
//c to the larger of each component pair
//c ddot = diameter reduction rate , larger of pair , m / s
//c wodot = dry loading loss rate for larger of pair
//c
//c Constant parameters
//c
//c u = mean horizontal windspeed at top of fuelbed
//c d = fuelbed depth
//c r0 = minimum value of mixing parameter
//c dr = max - min value of mixing parameter
//c ch2o = specific heat capacity of water , J / kg K
//c hvap = heat of vaporization of water J / kg
//c tpdry = temperature ( all components ) start drying ( K )
// real*4 wo( maxkl ) , alfa( maxno ) , dendry( maxno )
// real*4 fmois( maxno ) , cheat( maxno )
// real*4 condry( maxno ) , diam( maxkl ) , tpig( maxno )
// real*4 tchar( maxno ) , xmat( maxkl )
// real*4 tdry( maxkl ) , tign( maxkl )
// real*4 tout( maxkl ) , qcum( maxkl )
// real*4 tcum( maxkl ) , acum( maxkl )
// real*4 qdot( maxkl , MXSTEP ) , ddot( maxkl )
// real*4 wodot( maxkl ) , flit( maxno ) , fout( maxno )
// real*4 work( maxno )
bool BurnUp::Start(double dt, long now, long *ncalls)
{
long k, l, kl, nlit;
double delm, heatk, r, tf, ts, thd, tx, factor;
double conwet, dia, hg, hb, en, cpwet, fac;
double hf, dryt, tsd, c, tigk, e, dtign, trt;
double aint, ddt, dnext, wnext, df;
const double rindef=1.e+30;
//c Initialize time varying quantities and set up work( k )
//c The diameter reduction rate of fuel component k is given
//c by the product of the rate of heat transfer to it, per
//c unit surface area, and the quantity work( k )
for(k=1; k<=number; k++) //do k = 1 , number
{ fout[k-1]=0.0;
flit[k-1]=0.0;
alfa[k-1]=condry[k-1]/(dendry[k-1]*cheat[k-1]);
//c effect of moisture content on burning rate (scale factor)
delm=1.67* fmois[k-1];
//c effect of component mass density (empirical)
heatk=dendry[k-1] / 446.0;
//c empirical burn rate factor, J / cu m - K
heatk=heatk*2.01e+06*(1.0+delm);
//c normalize out driving temperature difference (Tfire - Tchar)
//c to average value of lab experiments used to find above constants
work[k-1]=1.0/(255.0*heatk);
for(l=0; l<=k; l++) //do l = 0 , k
{ kl=loc(k, l);
tout[kl]=rindef;
tign[kl]=rindef;
tdry[kl]=rindef;
tcum[kl]=0.0;
qcum[kl]=0.0;
}
}
//c Make first estimate of drying start times for all components
//c These times are usually brief and make little or no difference
r=r0+0.25*dr;
tf=TempF(fi, r);
ts=tamb;
if(tf<=(tpdry+10.0))
{ strcat(Message, " STOP: Igniting fire cannot dry fuel");
return false;
}
thd=(tpdry-ts)/(tf-ts);
tx=0.5*(ts+tpdry);
//tpamb=tamb;
for(k=1; k<=number; k++) //do k = 1 , number
{ factor=dendry[k-1]*fmois[k-1];
conwet=condry[k-1]+4.27e-04*factor;
for(l=0; l<=k; l++) //do l = 0 , k
{ kl=loc(k, l);
dia=diam[kl];
HeatExchange(dia, tf, tx, &hf, &hb, conwet, &en);
dryt=DryTime(en, thd);
cpwet=cheat[k-1]+fmois[k-1]*ch2o;
fac=pow2(0.5*dia)/conwet;
fac=fac*dendry[k-1]*cpwet;
dryt=fac*dryt;
tdry[kl]=dryt;
}
}
//c Next , determine which components are alight in spreading fire
tsd=tpdry;
for(k=1; k<=number; k++) //do k = 1 , number
{ c=condry[k-1];
tigk=tpig[k-1];
for(l=0; l<=k; l++) //do l = 0 , k
{ kl=loc(k, l);
dryt=tdry[kl];
if(dryt>=dt)
continue;
dia=diam[kl];
ts=0.5*(tsd+tigk);
HeatExchange(dia, tf, ts, &hf, &hb, c, &e);
tcum[kl]=max((tf-ts)*(dt-dryt), 0.0);
qcum[kl]=hb * tcum[kl];
if(tf<=(tigk+10.0))
continue;
dtign=TIgnite(tpdry, tpig[k-1], tf, condry[k-1], cheat[k-1], fmois[k-1], dendry[k-1], hb);
trt=dryt+dtign;
tign[kl]=0.5*trt;
if(dt>trt)
flit[k-1]+=xmat[kl];
}
}
nlit = 0;
trt = rindef;
//c Determine minimum ignition time and verify ignition exists
for(k=1; k<=number; k++) //do k = 1 , number
{ if(flit[k-1]>0.0)
nlit+=1;
for(l=0; l<=k; l++) //do l = 0 , k
{ kl=loc(k, l);
trt=min(trt, tign[kl]);
}
}
if(nlit==0)
{ strcat(Message, " STOP: No Fuel Ignited");
return false;
}
//c Deduct trt from all time estimates , resetting time origin
for(k=1; k<=number; k++) //do k = 1 , number
{ for(l=0; l<=k; l++)// do l = 0 , k
{ kl = loc(k, l);
if(tdry[kl]<rindef)
tdry[kl]-=trt;
if(tign[kl]<rindef)
tign[kl]-=trt;
}
}
//c Now go through all component pairs and establish burning rates
//c for all the components that are ignited; extrapolate to end time dt
for(k=1; k<=number; k++) //do k = 1 , number
{ if(flit[k-1]==0.0)
{ for(l=0; l<=k; l++)// do l = 0 , k
{ kl=loc(k, l);
ddot[kl]=0.0;
tout[kl]=rindef;
wodot[kl]=0.0;
}
}
else
{ ts=tchar[k-1];
c=condry[k-1];
for(l=0; l<=k; l++) //do l = 0 , k
{ kl=loc(k, l);
dia=diam[kl];
HeatExchange(dia, tf, ts, &hf, &hb, c, &e);
qdot[kl][now-1]=hb*max((tf-ts), 0.0);
aint=pow2(c/hb);
ddt=dt-tign[kl];
acum[kl]=aint * ddt;
ddot[kl]=qdot[kl][now-1]*work[k-1];
tout[kl]=dia/ddot[kl];
dnext=max(0.0, (dia-ddt*ddot[kl]));
wnext=wo[kl]*pow2(dnext/dia);
wodot[kl]=(wo[kl]-wnext)/ddt;
diam[kl]=dnext;
wo[kl]=wnext;
df=0.0;
if(dnext<=0.0)
{ df=xmat[kl];
wodot[kl]=0.0;
ddot[kl]=0.0;
}
flit[k-1]-=df;
fout[k-1]+=df;
}
}
}
*ncalls = 0;
return true;
}
//------------------------------------------------------------------------------
//
// Sorter
//
//------------------------------------------------------------------------------
// subroutine SORTER( maxno , number , sigma , fmois , dendry , key )
//
//c Sorts fuel element list in order of increasing size (decreasing sigma)
//c For elements with same size, order determined on increasing moisture
//c content (fmois). If items have same size and moisture content, order
//c on the basis of increasing mass density (dendry). "number" elements are
//c included in the list, which has a maximum length of "maxno". The integer
//c list: key( j ) , j = 1 , number holds the indices in order, so other
//c fuel parameters can be ordered and associated as necessary.
// real*4 sigma( maxno ) , fmois( maxno ) , dendry( maxno )
// integer key( maxno )
void BurnUp::Sorter()
{
long i, j, keep;
double s, fm, de, usi;
bool diam, mois, dens, tied, earlyout;
for(j=0; j<MAXNO; j++) //do j=1 , maxno
key[j]=j;
//c Replacement sort: order on increasing size , moisture , density
for(j=2; j<=number; j++) //do j = 2 , number
{ s=1.0/sigma[j-1];
fm = fmois[j-1];
de = dendry[j-1];
keep = key[j-1];
for(i=(j-2); i>=0; i--) //do i = ( j - 1 ) , 1 , -1
{ earlyout=true;
usi = 1.0/sigma[i];
if(usi<s)
diam=true;
else
diam=false;
if(diam)
break;// goto 10
if(usi==s)
tied=true;
else
tied=false;
if(tied) //goto 05
{ if(fmois[i]<fm)
mois=true;
else
mois=false;
if( mois )
break; //goto 10
if(fmois[i]==fm)
tied=true;
else
tied=false;
if(tied)
{ if(dendry[i]<=de)
dens=true;
else
dens=false;
if(dens)
break;// goto 10
}
}
sigma[i+1]=sigma[i];
fmois[i+1]=fmois[i];
dendry[i+1]=dendry[i];
key[i+1]=key[i];
earlyout=false;
}
if(!earlyout)
i=0;
sigma[i+1]=1.0/s;
fmois[i+1]=fm;
dendry[i+1]=de;
key[i+1]=keep;
}
}
//------------------------------------------------------------------------------
//
// OvLaps
//
//------------------------------------------------------------------------------
void BurnUp::OverLaps()
{
// wdry , sigma , dendry , ak , number , maxno , maxkl , beta , elam , alone , area )
// Computes the interaction matrix elam( j , k ) which apportions the
// influence of smallxer and equal size pieces on each size class for the
// purpose of establishing the rates at which the elements burn out.
// Input quantities are: wdry , the ovendry mass per unit area of each
// element available for burning after the passage of the igniting surface
// fire; sigma , the particle's surface / volume ratio , and dendry , the
// ovendry mass density of the particle; ak a dimensionless parameter that
// scales the planform area of a particle to its area of influence. There
// are "number" separate particle classes, of a maximum number = maxno.
// It is assumed that the lists are ordered on size class (nonincreasing
// surface / volume ratio). List "alone" gives the fraction of each loading
// that is not influenced by any other category.
//double wdry[MAXNO] , sigma[MAXNO] , dendry[MAXNO];
//double beta[MAXKL] , elam[MAXNO][MAXNO] , alone[MAXNO];
//double area[MAXNO];
long j, k, l, kj, kl;
double a, bb, pi, siga, frac;
pi = fabs(acos(-1.0));
for(j=1; j<=number; j++) //do j = 1 , number
{ alone[j-1]=0.0;
for(k=1; k<=j; k++)// do k = 1 , j
{ kj = loc(j, k);
xmat[kj]=0.0;
}
for(k=1; k<=number; k++) //do k = 1 , number
elam[j-1][k-1] = 0.0;
}
for(k=1; k<=number; k++) // do k = 1 , number
{ for(l=1; l<=k; l++) //do l = 1 , k
{ ak=3.25*exp(-20.0*pow2(fmois[l-1]));
siga = ak * sigma[k-1]/pi;
kl = loc(k, l);
a = siga*wdry[l-1]/dendry[l-1];
if(k==l)
{ bb = 1.0 - exp(-a);
if(bb<1e-30)
bb=1e-30;
area[k-1]=bb;
}
else //if(k!=1)
bb = min(1.0, a);
xmat[kl]=bb;
}
}
if(number==1)
{ elam[0][0]=xmat[1];
alone[0]=1.0- elam[0][0];
return;
}
for(k=1; k<=number; k++) // do k = 1 , number
{ frac=0.0;
for(l=1; l<=k; l++) // do l = 1 , k
{ kl=loc(k, l);
frac+=xmat[kl];
}
if(frac>1.0)
{ for(l=1; l<=k; l++) //do l = 1 , k
{ kl=loc(k, l);
elam[k-1][l-1]=xmat[kl]/frac;
}
alone[k-1]=0.0;
}
else
{ for(l=1; l<=k; l++) // do l = 1 , k
{ kl=loc(k, l);
elam[k-1][l-1]=xmat[kl];
}
alone[k-1]=1.0-frac;
}
}
}
//------------------------------------------------------------------------------
//
// subroutine HEATX()
//
//------------------------------------------------------------------------------
void BurnUp::HeatExchange(double dia , double tf , double ts ,
double *hfm , double *hbar , double cond, double *en)// returns en
{
// Given horizontal windspeed u at height d [top of fuelbed], cylindrical
// fuel particle diameter dia, fire environment temperature tf, and mean
// surface temperature, ts, subroutine returns film heat transfer coefficient
// hfm and an "effective" film heat transfer coefficient including radiation
// heat transfer, hbar. Using the wood's thermal conductivity, cond, the
// modified Nusselt number [ en ] used to estimate onset of surface drying
// is returned as well.
double v, re, enuair, conair, fac, hfmin;
const double g = 9.8;
const double vis = 7.5e-05;
const double a = 8.75e-03;
const double b = 5.75e-05;
const double rad = 5.67e-08;
const double fmfac = 0.382;
const double hradf = 0.5;
double hrad;
*hfm = 0.0;
if(dia>b)
{ v =sqrt(u*u+0.53*g*d);
re =v*dia/vis;
enuair =0.344*pow(re, 0.56);
conair =a+b*tf;
fac =sqrt(fabs(tf-ts)/dia);
hfmin =fmfac*sqrt(fac);
*hfm =max((enuair*conair/dia), hfmin);
}
hrad=hradf*rad*(tf+ts)*(tf*tf+ts*ts);
*hbar=*hfm+hrad;
*en=*hbar*dia/cond;
}
//------------------------------------------------------------------------------
//
// FIRINT.CPP
//
//------------------------------------------------------------------------------
double BurnUp::FireIntensity()
{
//wodot , ash , htval , maxno , number , maxkl , area , fint , fi )
// Computes fi = site avg fire intensity given the burning rates of all
// interacting pairs of fuel components [ wodot ] , the mineral ash content
// of each component [ ash ] , the heat of combustion value [ htval ] for
// each , and the number of fuel components [ number ] , where max = maxno.
// fi is in kW / sq m , while htval is in J / kg.
// fint( k ) is the correction to fi to adjust
// the intensity level to be the local value where size k is burning.
// real*4 ash( maxno ) , htval( maxno )
// real*4 wodot( maxkl ) , area( maxno ) , fint( maxno )
// data smallx / 1.e-06 /
long k, l, kl, k0;
double sum, wdotk, ark, term;
double wnoduff, wnoduffsum, noduffsum, test, noduffterm;//, fintnoduff[MAXNO];
double fracf;
sum=noduffsum=wnoduffsum=0.0;
for(k=1; k<=number; k++)
{ wdotk=wnoduff=0.0;
for(l=0; l<=k; l++)
{ kl = loc(k, l);
wdotk+=wodot[kl];
//if(l>0)
// wnoduff+=wodot[kl];
//else
// Smoldering[k-1]+=wodot[kl];
}
term=(1.0-ash[k-1])*htval[k-1]*wdotk*1.e-03;
ark=area[k-1];
if(ark>smallx)
fint[k-1]=term/ark-term;
else
fint[k-1] = 0.0;
k0=loc(k, 0);
Smoldering[k-1]=wodot[k0];
wnoduff=wdotk-Smoldering[k-1];
noduffterm=(1.0-ash[k-1])*htval[k-1]*wnoduff*1.e-03;
if(wnoduff>0.0)
{ fracf=wnoduff/wdotk;
test=fracf*fint[k-1];
}
else
test=0.0;
//--------------------------------------
// flaming and smoldering decision here
//--------------------------------------
if(test>FintSwitch/ark-FintSwitch)
Flaming[k-1]+=wnoduff; //wdotk;
else
Smoldering[k-1]+=wnoduff; //wdotk;
//--------------------------------------
//--------------------------------------
sum+=term;
noduffsum+=noduffterm;
wnoduffsum+=wnoduff;
}
return sum;
}
void BurnUp::SetFintSwitch(double fint)
{
FintSwitch=fint;
}
long BurnUp::GetFintSwitch()
{
return FintSwitch;
}
//------------------------------------------------------------------------------
//
// subroutine DRYTIM( enu , theta , tau )
//
//------------------------------------------------------------------------------
double BurnUp::func(double h, double theta)
{
const double a = 0.7478556;
const double b = 0.4653628;
const double c = 0.1282064;
return h*(b-h*(c-h))-(1.0-theta)/a;
}
double BurnUp::DryTime(double enu, double theta)
{
// Given a Nusselt number ( enu , actually Biot number = h D / k )
// and the dimensionless temperature rise required for the start
// of surface drying ( theta ), returns the dimensionless time ( tau )
// needed to achieve it. The time is given multiplied by thermal
// diffusivity and divided by radius squared. Solution by binary search.
long n;
double tau;
double x, xl, xh, xm;
const double p = 0.47047;
xl=0.0;
xh=1.0;
for(n=0; n<15; n++)
{ xm=0.5*(xl+xh);
if(func(xm, theta)<0.0)
xl = xm;
else
xh = xm;
}
x=(1.0/xm-1.0)/p;
tau=pow2(0.5*x/enu);
return tau;
}
//------------------------------------------------------------------------------
//
// Stash
//
//------------------------------------------------------------------------------
// subroutine STASH( time , now , maxno , number , outfil , fi ,
// + flit , fout , wo , wodot , diam , ddot ,
// + tdry , tign , tout , fmois , maxkl , nun )
//c This routine stashes output from the BURNUP model package on a snapshot
//c basis. Every time it is called, it "dumps" a picture of the status of
//c each component of the fuel complex, as a table of interacting pairs.
// real*4 wo( maxkl ) , wodot( maxkl )
// real*4 diam( maxkl ) , ddot( maxkl )
// real*4 flit( maxno ) , fout( maxno )
// real*4 tdry( maxkl ) , tign( maxkl )
// real*4 tout( maxkl ) , fmois( maxno )
// character*12 outfil , histry
// logical snaps
void BurnUp::Stash(char *HistFile, char *SnapFile, double time, long now)
{
long m, mn, n;
double wd, wg, wgm;
double wdm, wgf, wdf, fmm;
FILE *histfile, *snapfile;
if(now==1)// if( now .EQ. 1 ) then
{ histfile=fopen(HistFile, "w");
snapfile=fopen(SnapFile, "w");
wd = 0.0;
wg = 0.0;
for(m=1; m<=number; m++) //do m = 1 , number
{ fmm = fmois[m-1];
wdm = 0.0;
for(n=0; n<=m; n++) //do n = 0 , m
{ mn = loc(m, n);
wdm = wdm + wo[mn];
}
wgm=wdm*(1.0+fmm);
wd+=wdm;
wg+=wgm;
}
wd0=wd;
wg0=wg;
}
else
{ histfile=fopen(HistFile, "a");
snapfile=fopen(SnapFile, "a");
}
fprintf(snapfile, "\n%lf %lf\n", time, fi);
wd=0.0;
wg=0.0;
for(m=1; m<=number; m++) //do m = 1 , number
{ fmm=fmois[m-1];
wdm=0.0;
fprintf(snapfile, "%lf %lf %lf\n", time, flit[m-1], fout[m-1]);
for(n=0; n<=m; n++) //do n = 0 , m
{ mn=loc(m, n);
wdm+=wo[mn];//(wo[mn]*wodot[mn]*dt);
fprintf(snapfile, " %lf %lf %lf %lf %lf %lf %lf %lf\n",
time, wo[mn], wodot[mn], diam[mn], ddot[mn], tdry[mn], tign[mn], tout[mn]);
}
fprintf(snapfile, "\n");
wgm=wdm*(1.0+fmm);
wd+=wdm;
wg+=wgm;
}
wgf = wg/wg0;
wdf = wd/wd0;
fprintf(histfile, "%lf %lf %lf %lf %lf %lf\n", time, wg, wd, wgf, wdf, fi);
fclose(histfile);
fclose(snapfile);
}
bool BurnUp::AllocBurnStruct()
{
FreeBurnStruct();
bs=new BurnStruct[ntimes];
if(bs==NULL)
return false;
ZeroMemory(bs, ntimes*sizeof(BurnStruct));
return true;
}
void BurnUp::FreeBurnStruct()
{
if(bs)
delete[] bs;
bs=0;
}
void BurnUp::SetBurnStruct(double time, long now)
{
long i, m, mn, n;
double wd;
double wdm, wdf;
double wt[2]={0.0, 0.0};
if(now==1)// if( now .EQ. 1 ) then
{ wd = 0.0;
for(m=1; m<=number; m++) //do m = 1 , number
{ wdm = 0.0;
for(n=0; n<=m; n++) //do n = 0 , m
{ mn = loc(m, n);
wdm = wdm + wo[mn];
}
wd+=wdm;
}
wd0=wd;
}
wd=0.0;
for(m=1; m<=number; m++) //do m = 1 , number
{ wdm=0.0;
for(n=0; n<=m; n++) //do n = 0 , m
{ mn=loc(m, n);
wdm+=wo[mn];//(wo[mn]*wodot[mn]*dt);
}
wd+=wdm;
}
wdf = wd/wd0;
for(i=0; i<MAXNO; i++)
{ wt[0]+=Flaming[i];
wt[1]+=Smoldering[i];
Flaming[i]=Smoldering[i]=0.0;
}
wt[1]+=Smoldering[MAXNO];
if(now>ntimes) // don't overflow the buffer
return;
bs[now-1].time=time;
bs[now-1].wdf=wdf;
if(wt[0]+wt[1]>0.0)
bs[now-1].ff=wt[0]/(wt[0]+wt[1]);
else
bs[now-1].ff=0.0;
}
bool BurnUp::Summary(char *OutFile)
{
long m, n, mn;
double fr, ti, ts, to, tf, wd, rem, di;
FILE *outfile;
if((outfile=fopen(OutFile, "w"))==NULL)
return false;
fprintf(outfile, "%s\t %s\t %s\t %s\t %s\t %s\t %s\t %s\n", "#", "wt", "fmst", "~D", "ts", "tf", "rem", "%rem");
for(m=1; m<=number; m++)
{ fprintf(outfile, "%3ld\t %3.2lf\t %3.2lf\t %3.2lf\t", m, wdry[m-1], fmois[m-1], 4.0/sigma[m-1]);
rem=0.0;
ts=1.0e31;
tf=0.0;
for(n=0; n<=m; n++)
{ mn = loc(m, n);
fr = xmat[mn];
ti = tign[mn];
ts = min(ti, ts);
to = tout[mn];
tf = max(to, tf);
wd = wo[mn];
rem = rem + wd;
di = diam[mn];
// fprintf(outfile, "\n %ld %lf %lf %lf %lf", n, fr, ti, to, wd, di);
}
fprintf(outfile, " %8.2lf\t %10.2lf\t %3.4lf\t %3.2lf\n", ts, tf, rem, rem/wdry[m-1]);
}
fclose(outfile);
return true;
}
//------------------------------------------------------------------------------
//
// CurveFit Stuff
//
//------------------------------------------------------------------------------
/*
long BurnUp::GetRegressionCoefficients(double **coefs, long *NumCalcs)
{
*coefs=aa;
*NumCalcs=now;
return ma;
}
*/
bool BurnUp::AllocRegressionData(long ndata)
{
if(ndata>=NumAllocRegrData)
{ FreeRegressionData(ndata);
x=new double[ndata];
y=new double[ndata];
if(x==NULL || y==NULL)
{ FreeRegressionData(ndata);
return false;
}
NumAllocRegrData=ndata;
}
ZeroMemory(x, ndata*sizeof(double));
ZeroMemory(y, ndata*sizeof(double));
return true;
}
void BurnUp::FreeRegressionData(long /*ndata*/)
{
if(x)
delete[] x;
if(y)
delete[] y;
x=y=0;
NumAllocRegrData=0;
}
long BurnUp::GetSamplePoints(long Flaming, long NumberOfPts)//, double **xs, double **ys, long *numcalcs)
{
long i, j;
long NewPointPos, *pts, NewPoint, NumInSample, MaxNum;
double NewX, NewY;
double interval, xtest, ytest, ymid, ydiff, ymax;
ma=NumberOfPts;
if(ma<4)
ma=4;
AllocRegressionData(ma);
pts=new long[ma];
NumInSample=3;
if(Flaming) // find end of flaming period
{ for(i=0; i<now; i++)
{ if(bs[i].ff>0.0)
MaxNum=i;
}
MaxNum++;
}
else
MaxNum=now;
MaxNum--;
while(bs[MaxNum].time==0.0)
{ MaxNum--;
if(MaxNum<0)
break;
}
interval=(double) (MaxNum)/(double) NumInSample;
// fill out the initial array
if(interval==0)
{ if(pts)
delete[] pts;
return NumInSample;
}
else if(interval<1.0)
interval=1.0;
NumInSample++;
for(i=0; i<NumInSample; i++)
{ j=(long)((double) i * interval);
//GetBurnStruct(j, &bpx);
pts[i]=j;
x[i]=bs[j].time/60.0;
if(!Flaming)
y[i]=bs[j].wdf; // for nonlinear stuff and .wdf
else
y[i]=bs[j].ff;
}
NewPointPos=0;
NewPoint=1;
NewX=x[0];
do
{ // check error for individual spans
ymax=0.0;
for(i=1; i<NumInSample; i++)
{ interval=pts[i]-pts[i-1];
j=(long) ((double) pts[i-1] + interval/2.0);
if(j<1)
continue;
//GetBurnStruct(j, &bpx);
xtest=bs[j].time/60.0;//bpx.time/3600.0;
if(!Flaming)
ytest=bs[j].wdf;//bpx.wdf; // for nonlinear stuff and .wdf
else
ytest=bs[j].ff;//bpx.fi;
if(fabs(x[i-1]-x[i])>1e-6)
{ ymid=y[i-1]-(y[i-1]-y[i])*(x[i-1]-xtest)/(x[i-1]-x[i]);
ydiff=fabs(ymid-ytest);
if(ydiff>ymax)
{ ymax=ydiff;
NewX=xtest;
NewY=ytest;
NewPointPos=i;
NewPoint=j;
}
}
}
if(NewX!=x[NewPointPos])
{ MoveMemory(&x[NewPointPos+1], &x[NewPointPos], (NumInSample-NewPointPos)*sizeof(double));
MoveMemory(&y[NewPointPos+1], &y[NewPointPos], (NumInSample-NewPointPos)*sizeof(double));
MoveMemory(&pts[NewPointPos+1], &pts[NewPointPos], (NumInSample-NewPointPos)*sizeof(long));
x[NewPointPos]=NewX;
y[NewPointPos]=NewY;
pts[NewPointPos]=NewPoint;
NumInSample++;
}
else
ma--;
} while(NumInSample<ma);
if(pts)
delete[] pts;
//*xs=x;
//*ys=y;
//*numcalcs=MaxNum;
return ma;
}
bool BurnUp::GetSample(long num, double *xpt, double *ypt)
{
if(num<NumAllocRegrData)
{ *xpt=x[num];
*ypt=y[num];
return true;
}
return false;
}
bool BurnUp::GetBurnStruct(long Num, BurnStruct *Bs)
{
if(Num>now-1)
return false;
*Bs=bs[Num];
return true;
}
long BurnUp::GetNumOutputData()
{
return now;
}
/*
void polynom(double x, double a[], long n);
void polynom(double x, double a[], long n)
{
long i;
a[1]=1.0;
for(i=2; i<=n; i++)
a[i]=a[i-1]*x;
}
long BurnUp::RunPolynomialRegression(long Flaming)
{
long ndata;
long i, j, maxnum;
double maxval;
double oldchisq, chisq;
double tempaa[20]={0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
maxval=0.0;
maxnum=0;
for(i=0; i<now; i++)
{ if(bs[i].wdf>maxval) // really just using weight loss %
{ maxval=bs[i].wdf;
maxnum=i;
}
}
ndata=now-maxnum;
if(AllocRegressionData(ndata)==false)
return 0;
j=-1;
if(Flaming)
{ for(i=maxnum; i<now; i++)
{ j++;
x[j]=bs[i].time/60.0;
y[j]=bs[i].ff; // for nonlinear stuff and .wdf
}
}
else
{ for(i=maxnum; i<now; i++)
{ j++;
x[j]=bs[i].time/60.0;
y[j]=bs[i].wdf; // for nonlinear stuff and .wdf
}
}
for(i=0; i<ndata; i++)
sig[i]=1;///=maxval+0.00001;
if(!Flaming)
{ sig[ndata-1]=0.01;
sig[0]=0.01; // no weighted regression with intensity data
}
// find regression with minimum chi-squared, start with 4 parameters
ma=4;
LinearModel(ma, ndata, &chisq);
memcpy(tempaa, aa, 4*sizeof(double));
oldchisq=chisq;
for(i=5; i<20; i++)
{ LinearModel(i, ndata, &chisq);
if(oldchisq-chisq>0.01)
{ oldchisq=chisq;
memcpy(tempaa, aa, i*sizeof(double));
ma=i;
}
else
break;
}
memcpy(aa, tempaa, 20*sizeof(double));
return ma;
}
long BurnUp::LinearModel(long ma, long ndata, double *Chisq)
{
double chisq;
vx=dmatrix(1, ma, 1, ma);
svdfit(x-1, y-1, sig-1, ndata, aa-1, ma, ux, vx, w, &chisq, (*polynom));
*Chisq=chisq;
if(vx)
GlobalFree_dmatrix(vx, 1, ma, 1, ma);
vx=0;
return ndata;
}
*/
| [
"kyle@pobox.com"
] | kyle@pobox.com |
af9f437e2fd28e26933b59f51a2dd3432b8309a4 | ef7f3ee0f60aa7d0673b7b2371762d053e13a1e3 | /sidak/competitive.cpp | 77d823a12bc2d718926c5271069c566d417772d5 | [] | no_license | sidakwalia/c-code | d571a105e5a3df1a71b8a7eb576dd3856ca50763 | 76509573814c608fa75cce7bee779f49cd17e1c4 | refs/heads/master | 2021-05-22T15:55:02.722813 | 2020-04-04T18:22:58 | 2020-04-04T18:22:58 | 252,991,419 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 519 | cpp | #include<iostream>
using namespace std;
void printArr(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
void sum(int arr[],int n){
if(n<3)
return ;
int first=arr[0];
int second=arr[1];
for(int i=0;i<n-2;i++){
arr[i]=arr[i+1]+arr[i+2];
arr[n - 2] = arr[n - 1] + first;
arr[n - 1] = first + second;
printArr(arr,n);
}
}
int main(){
int arr[] = { 3,4,2,1,6};
int n = sizeof(arr) / sizeof(arr[0]);
sum(arr,n);
return 0;}
| [
"sidakw@gmail.com"
] | sidakw@gmail.com |
565e2b3d13a87d627a5b2c4f8a96f31c56334d7e | d93159d0784fc489a5066d3ee592e6c9563b228b | /JetMETCorrections/FFTJetObjects/interface/FFTJetRcdMapper.h | 88cce934c331f37fc23640f0529565ec6868fee7 | [] | permissive | simonecid/cmssw | 86396e31d41a003a179690f8c322e82e250e33b2 | 2559fdc9545b2c7e337f5113b231025106dd22ab | refs/heads/CAallInOne_81X | 2021-08-15T23:25:02.901905 | 2016-09-13T08:10:20 | 2016-09-13T08:53:42 | 176,462,898 | 0 | 1 | Apache-2.0 | 2019-03-19T08:30:28 | 2019-03-19T08:30:24 | null | UTF-8 | C++ | false | false | 3,750 | h | #ifndef JetMETCorrections_FFTJetObjects_FFTJetRcdMapper_h
#define JetMETCorrections_FFTJetObjects_FFTJetRcdMapper_h
//
// A factory to combat the proliferation of ES record types
// (multiple record types are necessary due to deficiencies
// in the record dependency tracking mechanism). Templated
// upon the data type which records hold.
//
// Igor Volobouev
// 08/03/2012
#include <map>
#include <string>
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Utilities/interface/Exception.h"
template<class DataType>
struct AbsFFTJetRcdMapper
{
virtual ~AbsFFTJetRcdMapper() {}
virtual void load(const edm::EventSetup& iSetup,
edm::ESHandle<DataType>& handle) const = 0;
virtual void load(const edm::EventSetup& iSetup,
const std::string& label,
edm::ESHandle<DataType>& handle) const = 0;
};
template<class DataType, class RecordType>
struct ConcreteFFTJetRcdMapper : public AbsFFTJetRcdMapper<DataType>
{
virtual ~ConcreteFFTJetRcdMapper() {}
inline void load(const edm::EventSetup& iSetup,
edm::ESHandle<DataType>& handle) const
{iSetup.get<RecordType>().get(handle);}
inline void load(const edm::EventSetup& iSetup,
const std::string& label,
edm::ESHandle<DataType>& handle) const
{iSetup.get<RecordType>().get(label, handle);}
};
template<class DataType>
struct DefaultFFTJetRcdMapper :
public std::map<std::string, AbsFFTJetRcdMapper<DataType>*>
{
typedef DataType data_type;
inline DefaultFFTJetRcdMapper()
: std::map<std::string, AbsFFTJetRcdMapper<DataType>*>() {}
virtual ~DefaultFFTJetRcdMapper()
{
for (typename std::map<std::string, AbsFFTJetRcdMapper<DataType>*>::
iterator it = this->begin(); it != this->end(); ++it)
delete it->second;
}
inline void load(const edm::EventSetup& iSetup,
const std::string& record,
edm::ESHandle<DataType>& handle) const
{
typename std::map<std::string, AbsFFTJetRcdMapper<DataType>*>::
const_iterator it = this->find(record);
if (it == this->end())
throw cms::Exception("KeyNotFound")
<< "Record \"" << record << "\" is not registered\n";
it->second->load(iSetup, handle);
}
inline void load(const edm::EventSetup& iSetup,
const std::string& record,
const std::string& label,
edm::ESHandle<DataType>& handle) const
{
typename std::map<std::string, AbsFFTJetRcdMapper<DataType>*>::
const_iterator it = this->find(record);
if (it == this->end())
throw cms::Exception("KeyNotFound")
<< "Record \"" << record << "\" is not registered\n";
it->second->load(iSetup, label, handle);
}
private:
DefaultFFTJetRcdMapper(const DefaultFFTJetRcdMapper&);
DefaultFFTJetRcdMapper& operator=(const DefaultFFTJetRcdMapper&);
};
//
// Singleton for the mapper
//
template <class Mapper>
class StaticFFTJetRcdMapper
{
public:
typedef typename Mapper::Base::data_type data_type;
static const Mapper& instance()
{
static Mapper obj;
return obj;
}
template <class Record>
static void registerRecord(const std::string& record)
{
Mapper& rd = const_cast<Mapper&>(instance());
delete rd[record];
rd[record] = new ConcreteFFTJetRcdMapper<data_type,Record>();
}
private:
StaticFFTJetRcdMapper();
};
#endif // JetMETCorrections_FFTJetObjects_FFTJetRcdMapper_h
| [
"giulio.eulisse@gmail.com"
] | giulio.eulisse@gmail.com |
bbce506ffb62d5d739e3de18fb4e1adb7f71c059 | 44db1ec8d639d2e78583e2844e5de1b38a1ca26f | /C(++)/GFX/GDI01/GDI01/GDI01.cpp | 5e93e01c0df1cd3e86437e2db29ace56b489e1a7 | [] | no_license | braindef/code | adfb4e8980fd0fdbf23e051a5ffad72be22ae12d | f6fbaf3f1b1c41df391c706278b5bcb4e83d2ac2 | refs/heads/master | 2020-04-01T08:00:59.721124 | 2018-10-14T20:02:56 | 2018-10-14T20:02:56 | 153,013,739 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,845 | cpp |
#include <GDI01.h>
#include <windows.h>
#include <string.h> //für strcpy
#define MAXSIZE 500
LRESULT CALLBACK WinProc(HWND, UINT, WPARAM, LPARAM);
double hektor(long);
HINSTANCE hProgram;
HWND hWnd;
HDC hDC;
double x[MAXSIZE*MAXSIZE+1], y[MAXSIZE*MAXSIZE+1];
double z[MAXSIZE*MAXSIZE+1];
double result;
int itoggle=1;
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
PSTR scCmdLine, int iCmdShow)
{
extern HINSTANCE hProgram;
extern HWND hWnd;
MSG msg;
WNDCLASSEX wndclass;
char capname[3];
hProgram=hInstance;
strcpy(capname, "W4");
wndclass.cbSize = sizeof(wndclass);
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WinProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hProgram;
wndclass.hIcon = LoadIcon(hprogram, MB_ICONERROR);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = CreateSolidBrush(RGB(255,255,255));
wndclass.lpszMenuName = capname;
wndclass.lpszClassName = capname;
wndclass.hIcon = NULL;
RegisterClassEx(&wndclass);
hWnd=CreateWindow(capname, "Windows Programm", WS_OVERLAPPEDWINDOW, 100, 100, 540, 140, NULL, NULL, hProgram, NULL);
ShowWindow(hWnd, iCmdShow);
UpdateWindow(hWnd);
while(GetMessage(&msg);
{
TranslateMessage(&msg)
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WinProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM l Param)
{
extern HDC hDC;
PAINTSTRUCT ps;
RECT rect;
extern double result;
extern int itoggle;
switch(Message)
{
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDM_RECHNE:
hDC=GetDC(hWnd);
TextOut(hDC, 10, 10 "Start der Berechnung",20);
ReleaseDC(hWnd,hDC);
SetCursor(LoadCursor(NULL, IDC_WAIT));
result=hektor((long)MAXSIZE);
SetCursor(LoadCursor(NULL, IDC_ARROW));
hDC = GetDC(hWnd);
TextOut(hDC,10,70,"Ende der Berechnung!",20);
ReleaseDC(hWnd, hDC);
return 0;
case IDM_LOESCHEN:
rect.left=0;
rect.top=0;
rect.right=270;
rect.bottom=70;
InvalidateRect(hWnd, &rect, TRUE);
return 0;
case IDM_WERISTS_
MessageBox(NULL, "Windows Programm W4", "W4W, MB_OK | MB_ICONINFORMATION);
return 0;
case IDM_ENDE:
PostQuitMessage(0);
return 0;
}
case WM_PAINT:
hDC=BeginPaint(hWnd, &ps);
if(itoggle==1)
{
TextOut(hDC,300, 10, "WM_PAINT gesendet! ",22);
itoggle=0;
}
else
{
TextOut(hDC, 300, 10, " WM_PAINT gesendet !", 22);
itoggle=1;
}
EndPaint(hWnd, &ps);
return 0;
case WM_MOVE:
InvalidateRect(hWnd, NULL, TRUE);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hWnd, Message, wParam, lParam);
}
}
case
| [
"asdf@asdf.com"
] | asdf@asdf.com |
64208fa6abd9843898830983519145ffe2ab39b4 | eaf2c3ee81884c54137844315dc37b26bde11404 | /sfmf2/source/taskbar.cpp | 935e4b9568c4652c5b6c02c788b715f39e8d9318 | [] | no_license | sfpgmr/sfmf2 | fa2f4a9cf0f219f7f2e9570e51906128dcc98874 | 73091ed5ca0f9e8e7435e1779bce08dc3412ef48 | refs/heads/master | 2016-08-04T09:08:41.963714 | 2014-03-22T21:54:48 | 2014-03-22T21:54:48 | 14,905,785 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,948 | cpp | #include "StdAfx.h"
#if _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
#endif
#include "sf_windows.h"
#include "taskbar.h"
namespace sf {
const int taskbar::none = TBPF_NOPROGRESS;
const int taskbar::indeterminate = TBPF_INDETERMINATE;
const int taskbar::normal = TBPF_NORMAL;
const int taskbar::error = TBPF_ERROR;
const int taskbar::paused = TBPF_PAUSED;
long taskbar::register_message()
{
return ::RegisterWindowMessage(L"TaskbarButtonCreated");
}
struct taskbar::impl
{
typedef throw_if_err<sf::taskbar::exception> throw_if_err_;
impl(){}
~impl()
{
discard();
}
void create() {
throw_if_err_()(CoCreateInstance(CLSID_TaskbarList,nullptr,CLSCTX::CLSCTX_INPROC_SERVER,__uuidof(ITaskbarList4),(LPVOID*)taskbar_.GetAddressOf()));
}
bool is_create() const
{
return (taskbar_ != 0);
}
void discard()
{
safe_release(taskbar_);
}
void overlay_icon(const sf::base_window& w,const sf::icon& ic,const std::wstring& description)
{
throw_if_err_()(taskbar_->SetOverlayIcon(w.hwnd(),ic.get(),description.c_str()));
}
void progress_state(const sf::base_window& w,TBPFLAG state)
{
throw_if_err_()(taskbar_->SetProgressState(w.hwnd(),state));
}
void progress_value(const sf::base_window& w,boost::uint64_t completed, boost::uint64_t total)
{
throw_if_err_()(taskbar_->SetProgressValue(w.hwnd(),completed,total));
}
void add_thumb_buttons(const sf::base_window& w,const std::vector<THUMBBUTTON>& tbs){
taskbar_->ThumbBarAddButtons(w.hwnd(),tbs.size(),const_cast<LPTHUMBBUTTON>(&(tbs[0])));
};
void update_thumb_buttons(const sf::base_window& w,const std::vector<THUMBBUTTON>& tbs){
taskbar_->ThumbBarUpdateButtons(w.hwnd(),tbs.size(),const_cast<LPTHUMBBUTTON>(&(tbs[0])));
};
private:
_WRL_PTR_TYPEDEF(ITaskbarList4);
ITaskbarList4Ptr taskbar_;
};
taskbar::taskbar() : impl_(new sf::taskbar::impl()) {}
taskbar::~taskbar() { discard();};
void taskbar::create(){impl_->create();};
bool taskbar::is_create() const {return impl_->is_create();};
void taskbar::discard(){impl_->discard();};
void taskbar::overlay_icon(const sf::base_window& w,const icon& ic,const std::wstring& description){impl_->overlay_icon(w,ic,description);};
void taskbar::progress_state(const sf::base_window& w,int state){impl_->progress_state(w,(TBPFLAG)state);};
void taskbar::progress_value(const sf::base_window& w,boost::uint64_t completed, boost::uint64_t total){impl_->progress_value(w,completed,total);};
void taskbar::add_thumb_buttons(const sf::base_window& w,const thumb_button_manager& tm){
BOOST_ASSERT(!tm.is_added);
impl_->add_thumb_buttons(w,tm.thumbbuttons_);
tm.is_added = true;
};
void taskbar::update_thumb_buttons(const sf::base_window& w,const thumb_button_manager& tm){
BOOST_ASSERT(tm.is_added);
if(tm.is_added){
impl_->update_thumb_buttons(w,tm.thumbbuttons_);
}
};
} | [
"sfpgmr@gihub.com"
] | sfpgmr@gihub.com |
416d883b4203b13e145824ec280064926ee1773f | 005ead270fdff9ad85513d0b2e345dea11e2fbb4 | /Q040_Combination Sum II.cpp | f1cd96ec21b99ec245f23040524fce212d21e8c4 | [] | no_license | wangqinghe95/Code-Leetcode | 222d5d50e5f81b25549d61810618a50849fc3269 | 3cdcdf2047e0c41485817e04c8e23853e9332c63 | refs/heads/master | 2023-04-29T20:44:22.764343 | 2021-05-16T05:40:27 | 2021-05-16T05:40:27 | 274,806,554 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,094 | cpp | /*
在一个数组中找到和为target的组合
用一个hash映射来表示出现数字的值和次数关系
再用回溯直接求出所有可能
采用两个措施来剪枝
1、判断当前选中的值是否大于target(或者剩余的值是否大于0)
2、选择的数的个数是否超出总体个数
*/
class Solution {
vector<pair<int,int>> freq;
vector<vector<int>> ans;
vector<int> sequence;
public:
void dfs(int pos, int rest){
if(rest == 0){
ans.push_back(sequence);
return;
}
if (pos == freq.size() || rest < freq[pos].first){
return;
}
dfs(pos+1, rest);
int most = min(rest / freq[pos].first, freq[pos].second);
for (int i = 1; i <= most; ++i){
sequence.push_back(freq[pos].first);
dfs(pos+1, rest-i*freq[pos].first);
}
for(int i = 1; i <= most; ++i){
sequence.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
for(int num : candidates){
if (freq.empty() || num != freq.back().first){
freq.emplace_back(num, 1);
}
else{
++freq.back().second;
}
}
dfs(0, target);
return ans;
}
};
/*
方法二使用排序来代替方法一的频率
*/
\class Solution {
public:
vector<vector<int>> res;
vector<int> tmp;
void backtrace(vector<int>& candidates, int target, int index) {
if (0 == target) {
res.push_back(tmp);
return;
}
for (int i = index; i < candidates.size() && target - candidates[i] >= 0; ++i) {
if (i > index && candidates[i] == candidates[i - 1]) {
continue;
}
tmp.push_back(candidates[i]);
backtrace(candidates, target - candidates[i], i + 1);
tmp.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
backtrace(candidates, target, 0);
return res;
}
};
| [
"675072584@qq.com"
] | 675072584@qq.com |
78712305cb7823b556e6f3b8156418cbcb6b2c97 | a9a18e8bbe336b9c5e89d280c91a050c58f9ee01 | /node/c++_addon/hello.cc | 1af055ccac0c7801da436c2f9a6c56db51d2af26 | [] | no_license | dalent/gitcode | 1757ae95326f1080ceeaa58d25ee55ca1f275c8c | 53267bfae1f6268323639a3a28ee9aec381f87e0 | refs/heads/master | 2021-01-17T10:45:50.640395 | 2017-03-02T02:21:16 | 2017-03-02T02:21:16 | 13,564,066 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 342 | cc | #include <node.h>
#include <v8.h>
using namespace v8;
Handle<Value> Method(const Arguments& args) {
HandleScope scope;
return scope.Close(String::New("world"));
}
void init(Handle<Object> exports) {
exports->Set(String::NewSymbol("hello"),
FunctionTemplate::New(Method)->GetFunction());
}
NODE_MODULE(hello, init)
| [
"anqiu1987@sina.com"
] | anqiu1987@sina.com |
e4147390da9ad7c7f54e64c42c1e9e6812bba82f | 84cf2dc2cddb2e5963d8d5427183a364614f0e14 | /dec4/part2.cpp | 50662ae091ad411f427c16e1205e24e67d545b28 | [] | no_license | cmavrogiannis/adventofcode2017 | 1baba8500c13703f645ac8ca1a9606570b893edc | 0364352753a639dba3998ccff01384c58f41b139 | refs/heads/master | 2021-08-24T12:40:55.893253 | 2017-12-09T23:23:21 | 2017-12-09T23:23:21 | 113,380,944 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 740 | cpp | #include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
bool is_valid(istream &input)
{
vector<string> word;
string w;
string line;
getline(input,line);
istringstream is(line);
while(is >> w)
{
word.push_back(w);
}
int N = word.size();
for (int i{0}; i < N-1; i++)
{
for (int j{i+1}; j < N; j++ )
{
sort(word[i].begin(),word[i].end());
sort(word[j].begin(),word[j].end());
if ( word[i] == word[j] )
{
return false;
}
}
}
return true;
}
int main(int argc, char *argv[])
{
int n{0};
ifstream input("data.txt");
while(!input.eof())
{
if (is_valid(input))
{
n++;
}
}
cout << "the answer is " << n << endl;
return 0;
} | [
"ccmavrogiannis@gmail.com"
] | ccmavrogiannis@gmail.com |
2a8b577a4a9ef62bb0dc61820d0f831ed760b176 | b10c93bc8fb4973e2a5aa0f258326d8e18f92ef8 | /src/ParticleSystem.cpp | 562a4fad989396b71931abfbf6a7c24ffd0ccf17 | [] | no_license | erumeldir/musicVisualizer | 3138b6e68f183531c79096e9928f044f4b756eac | 61a9a4098722932ba295701fd407ba54127d53a2 | refs/heads/master | 2021-01-22T13:46:48.496495 | 2013-12-14T00:54:27 | 2013-12-14T00:54:27 | 14,517,434 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,912 | cpp | #include "ParticleSystem.h"
#include "SOIL.h"
ParticleSystem::ParticleSystem(Vector3 pos, int nParticles, double lifetime, char* spriteName, Shader* partShader)
{
// create space for all for the particles
particles = new Particle[nParticles];
numParticles = nParticles;
position = pos;
globalLifetime = lifetime;
particleSprite = SOIL_load_OGL_texture
(
spriteName,
SOIL_LOAD_AUTO,
SOIL_CREATE_NEW_ID,
SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT
);
if (0 == particleSprite)
{
printf("SOIL loading error: '%s'\n", SOIL_last_result());
}
particleShader = partShader;
}
ParticleSystem::~ParticleSystem()
{
// deallocate particle array
delete[] particles;
}
/*********************GETTERS AND SETTERSi*******************/
// gets position of system
Vector3 ParticleSystem::getPosition()
{
return position;
}
// sets position
void ParticleSystem::setPosition(Vector3 pos)
{
position = pos;
}
// gets particle in the particle array
Particle& ParticleSystem::getParticle(int particleNum)
{
return particles[particleNum];
}
// sets particle in the array to the given particle
void ParticleSystem::setParticle(int particleNum, Particle newValue)
{
particles[particleNum] = newValue;
}
// gets number of particles
int ParticleSystem::getNumParticles()
{
return numParticles;
}
// gets the reference point for all the lifetimes of the particles
int ParticleSystem::getGlobalLifetime()
{
return globalLifetime;
}
// sets the reference point for lifetimes of the particles
void ParticleSystem::setGlobalLifetime(int newLifetime)
{
globalLifetime = newLifetime;
}
// TODO: optimize this!!
// finds next available spot in the particle array and returns its index
// returns -1 if no spot was found
int ParticleSystem::findNext()
{
for (int i = 0; i < numParticles; i++)
{
if (particles[i].state == DEAD)
{
return i;
}
}
// no available spots right now
return -1;
}
// finds next avaialbe spot and makes it into new emitter
void ParticleSystem::triggerEmitter(Vector3 direction)
{
// find next available spot
int index = findNext();
// if there WAS an available spot
if (index != -1)
{
particles[index].state = ALIVE;
particles[index].p0 = position;
particles[index].lifetime = globalLifetime + rand() % 500;
particles[index].time = 0;
particles[index].v0 = direction;
}
}
/*
* draw
*
* overidden draw method from Node.
* updates each particles lifetimes,
* draws all of the children
* and passes them to the vertex shader
*/
void ParticleSystem::draw(Matrix4, Frustum, bool)
{
// turning on flag in shader
particleShader->uniform1i("particle", 1);
glActiveTexture(GL_TEXTURE0 + 2);
glBindTexture(GL_TEXTURE_2D, particleSprite);
particleShader->uniform1i("tex", 2);
glEnable(GL_POINT_SPRITE);
// get the current time
int currentTime = frameTimer.getElapsedTimeInMilliSec();
// array of vertices to pass to shader
float* vertices = new float[numParticles * 3];
float* initialVel = new float[numParticles * 3];
float* time = new float[numParticles];
glPointSize(7);
//glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
// update particles' existence time
for (int i = 0; i < numParticles; i++)
{
// initial position of current point
Vector3 currPoint = particles[i].p0;
// initial vel of current point
Vector3 currVel = particles[i].v0;
particles[i].time += currentTime - prevFrameTime;
// check if particle exceeds its lifetime
if (particles[i].time > particles[i].lifetime)
particles[i].reset();
else
{
if (particles[i].state == ALIVE)
{
// draw particles' vertices
glBegin(GL_POINTS);
glColor4f(1, 1, 1, 1);
Vector3 g(0, -9.8 * 30, 0);
float t = particles[i].time / 1000.0;
g.scale(0.5 * t * t);
currVel.scale(t);
currPoint += currVel + g;
glVertex3f(currPoint[0], currPoint[1], currPoint[2]);
glEnd();
}
else{
// draw particles' vertices
/* glBegin(GL_POINTS);
glColor4f(0,0,0,0);
glVertex3f(currPoint[0], currPoint[1], currPoint[2]);
glEnd();*/
}
}
glBindTexture(GL_TEXTURE_2D, 0);
// set initial position for vertex shader
vertices[i * 3] = currPoint[0];
vertices[i * 3 + 1] = currPoint[1];
vertices[i * 3 + 2] = currPoint[2];
// initial velocity for shader
initialVel[i * 3] = currVel[0];
initialVel[i * 3 + 1] = currVel[1];
initialVel[i * 3 + 2] = currVel[2];
// set time for shader
time[i] = particles[i].time;
}
// update prevTime
prevFrameTime = currentTime;
//
particleShader->uniform1i("particle", 0);
}
// overidden bounding sphere method from Node
void ParticleSystem::computeBoundingSphere(Matrix4)
{
} | [
"ding@ucsd.edu"
] | ding@ucsd.edu |
c7ff5731b2195f26cfba0441cdef4ca83d639f67 | bcf6d899cdb948b17cadff23cb229bc6992949d7 | /TP1/1°Lista/.Primeira Lista - Projetos UI end + UML/_PRONTO!!!/ProjetoPaciente/ProjetoPaciente/mainwindow.cpp | 86ba2992e9f1d3cb6e12fd472ade6a362d2975cd | [] | no_license | YugoVtr/QT | 06d8b10f6de6dc98e7be82799b6f3c16f0d9b2ce | 702985b63d5473529e407069e0945aca0c17acc1 | refs/heads/master | 2021-01-21T20:34:07.379678 | 2017-06-08T02:52:43 | 2017-06-08T02:52:43 | 92,247,583 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 978 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButtonCalcular_clicked()
{
try {//Monitoramento das exeções
//capturar as informações
QString nome = ui->lineEditNome->text();
int peso = ui->lineEditPeso->text().toInt();
float altura = ui->lineEditAltura->text().toFloat();
//Criar valore porpassar valores por parametro
PrimeiraLista::Paciente pacienteX;
pacienteX.setNome(nome);
pacienteX.setPeso(peso);
pacienteX.setAltura(altura);
//Variavel para saida
QString saida;
saida = pacienteX.getNome()+" esta "+pacienteX.calcularFaixaDePeso();
ui->lineEditSaida->setText(saida);
} catch (QString &erro) {
QMessageBox::information(this,"ERRO",erro);
}
}
| [
"vtrhg69@hotmail.com"
] | vtrhg69@hotmail.com |
8789090baa14bfba57009c25e7197f77f05c0adf | 25e1610996ec35ebc32bbadaf01c1706c754110e | /glorious/Debug.h | 28fd11ef05148bc54139dfb5d2746a08a0165c17 | [] | no_license | ianpas/glorious | 7f94f726945465a947cf583cf78c1a55c5e08f19 | 8ed3b7c1d552d97c7d2250f201a2d59606679171 | refs/heads/master | 2021-01-24T20:26:08.036898 | 2018-02-28T12:15:53 | 2018-02-28T12:15:53 | 123,251,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 170 | h | #pragma once
namespace Glorious
{
class Debug
{
public:
static void Log(std::string const& message);
static void PopMessageBox(std::string const& message);
};
}
| [
"ianpas@126.com"
] | ianpas@126.com |
7fba1477c13b05331f2f38f8288c871834f013a3 | ed9e559e7292285afce8070576eff1ac852af399 | /src/Widget.hpp | a6c7d97a998125f939bd3c73c9b8a06841af09b6 | [
"Unlicense"
] | permissive | tybl/goon | ea035853d098614d98d9c4b56a04b24f7bcb68fb | 9c7ae6e309457327465252f200964d95c8dfde17 | refs/heads/dev | 2023-09-01T10:57:53.373716 | 2023-08-18T19:36:22 | 2023-08-18T19:37:46 | 672,677,647 | 0 | 0 | Unlicense | 2023-08-18T19:37:48 | 2023-07-30T22:17:06 | C++ | UTF-8 | C++ | false | false | 506 | hpp | // License: The Unlicense (https://unlicense.org)
#include <SDL2/SDL.h>
struct widget {
widget(SDL_Renderer* p_renderer);
void render(SDL_Renderer* p_renderer);
void handle_keyboard_event(SDL_Keycode p_key);
void handle_window_event(SDL_WindowEvent p_key);
private:
void move_forward(void);
private:
double m_x_pos;
double m_x_vel;
double m_y_pos;
double m_y_vel;
double m_angle;
double m_angle_momentum;
int m_window_width;
int m_window_height;
SDL_Texture* m_texture;
};
| [
"t.brandon.lyons@gmail.com"
] | t.brandon.lyons@gmail.com |
2a9737e712be3e710a6d1dc1fec45bd9993f3359 | 8f72438d5f4ca7219df3ae7799c3282faab5e33e | /Uva/Uva - 1124 Celebrity jeopardy.cpp | b50076e1d1fa55f5974b24ca9c77e0e0d879c983 | [] | no_license | mdzobayer/Problem-Solving | 01eda863ef2f1e80aedcdc59bbaa48bcaeef9430 | a5b129b6817d9ec7648150f01325d9dcad282aed | refs/heads/master | 2022-08-15T22:04:18.161409 | 2022-08-08T11:46:00 | 2022-08-08T11:46:00 | 165,687,520 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 990 | cpp | #include <bits/stdc++.h>
using namespace std;
/// Read & Write to File Short-Cut
#define fRead(x) freopen(x, "r", stdin)
#define fWrite(x) freopen(x, "w", stdout)
/// Data type Short-Cut
#define LLI long long int
#define ULL unsigned long long int
#define ff first
#define ss second
#define mk make_pair
#define phb push_back
#define ppb pop_back
#define phf push_front
#define ppf pop_front
/// Input Short-Cut
#define scan(a) scanf("%d", &a);
#define scan2(a, b) scanf("%d %d", &a, &b);
#define scan3(a, b, c) scanf("%d %d %d", &a, &b, &c);
#define scan4(a, b, c, d) scanf("%d %d %d %d", &a, &b, &c, &d);
/// Utility
#define SQR(x) ((x) * (x))
#define PI acos(-1.0)
/// Fast Read and de-active buffer flash
#define FastRead std::cin.sync_with_stdio(false);std::cin.tie(nullptr);
///======================== Let's GO ========================
int main() {
FastRead
fRead("in.txt");
string s;
while(getline(cin, s)) {
cout << s << endl;
}
return (0);
}
| [
"mdzobayer@rocketmail.com"
] | mdzobayer@rocketmail.com |
582603f034c5e65c5645c63a5833769a0ea394e4 | 4b86dafab3b94532e4308988352a53659fa7b854 | /hls/resnet50_3/solution1/syn/systemc/dataflow_in_loop.cpp | d9dcd7f91b9978bc5b83929565cc739f89609260 | [] | no_license | sterngerlach/ResNet-50_INT8 | 22842ee435f8d7574f05b1c40aa82cb714df8edf | e813beb03158b7df5eee46e9382011a140f6ead2 | refs/heads/main | 2023-08-25T01:41:56.795030 | 2021-11-04T04:49:11 | 2021-11-04T04:49:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,438 | cpp | // ==============================================================
// RTL generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC
// Version: 2019.1.3
// Copyright (C) 1986-2019 Xilinx, Inc. All Rights Reserved.
//
// ===========================================================
#include "dataflow_in_loop.h"
#include "AESL_pkg.h"
using namespace std;
namespace ap_rtl {
const sc_logic dataflow_in_loop::ap_const_logic_1 = sc_dt::Log_1;
const sc_lv<4> dataflow_in_loop::ap_const_lv4_0 = "0000";
const sc_logic dataflow_in_loop::ap_const_logic_0 = sc_dt::Log_0;
const sc_lv<1024> dataflow_in_loop::ap_const_lv1024_lc_1 = "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
const sc_lv<10> dataflow_in_loop::ap_const_lv10_0 = "0000000000";
const sc_lv<32> dataflow_in_loop::ap_const_lv32_0 = "00000000000000000000000000000000";
const sc_lv<2> dataflow_in_loop::ap_const_lv2_0 = "00";
const sc_lv<2> dataflow_in_loop::ap_const_lv2_1 = "1";
const sc_lv<1> dataflow_in_loop::ap_const_lv1_0 = "0";
const sc_lv<1> dataflow_in_loop::ap_const_lv1_1 = "1";
const sc_lv<3> dataflow_in_loop::ap_const_lv3_0 = "000";
const sc_lv<128> dataflow_in_loop::ap_const_lv128_lc_1 = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
const sc_lv<16> dataflow_in_loop::ap_const_lv16_0 = "0000000000000000";
dataflow_in_loop::dataflow_in_loop(sc_module_name name) : sc_module(name), mVcdFile(0) {
weight_V_U = new dataflow_in_loop_weight_V("weight_V_U");
weight_V_U->clk(ap_clk);
weight_V_U->reset(ap_rst);
weight_V_U->i_address0(fc_load_weight_U0_weight_V_address0);
weight_V_U->i_ce0(fc_load_weight_U0_weight_V_ce0);
weight_V_U->i_we0(fc_load_weight_U0_weight_V_we0);
weight_V_U->i_d0(fc_load_weight_U0_weight_V_d0);
weight_V_U->i_q0(weight_V_i_q0);
weight_V_U->t_address0(fc_compute_1_U0_weight_V_address0);
weight_V_U->t_ce0(fc_compute_1_U0_weight_V_ce0);
weight_V_U->t_we0(ap_var_for_const0);
weight_V_U->t_d0(ap_var_for_const1);
weight_V_U->t_q0(weight_V_t_q0);
weight_V_U->i_ce(ap_var_for_const2);
weight_V_U->t_ce(ap_var_for_const2);
weight_V_U->i_full_n(weight_V_i_full_n);
weight_V_U->i_write(fc_load_weight_U0_ap_done);
weight_V_U->t_empty_n(weight_V_t_empty_n);
weight_V_U->t_read(fc_compute_1_U0_ap_ready);
fc_load_weight_U0 = new fc_load_weight("fc_load_weight_U0");
fc_load_weight_U0->ap_clk(ap_clk);
fc_load_weight_U0->ap_rst(ap_rst);
fc_load_weight_U0->ap_start(fc_load_weight_U0_ap_start);
fc_load_weight_U0->ap_done(fc_load_weight_U0_ap_done);
fc_load_weight_U0->ap_continue(fc_load_weight_U0_ap_continue);
fc_load_weight_U0->ap_idle(fc_load_weight_U0_ap_idle);
fc_load_weight_U0->ap_ready(fc_load_weight_U0_ap_ready);
fc_load_weight_U0->weight_V_address0(fc_load_weight_U0_weight_V_address0);
fc_load_weight_U0->weight_V_ce0(fc_load_weight_U0_weight_V_ce0);
fc_load_weight_U0->weight_V_we0(fc_load_weight_U0_weight_V_we0);
fc_load_weight_U0->weight_V_d0(fc_load_weight_U0_weight_V_d0);
fc_load_weight_U0->m_axi_ddr_V_AWVALID(fc_load_weight_U0_m_axi_ddr_V_AWVALID);
fc_load_weight_U0->m_axi_ddr_V_AWREADY(ap_var_for_const0);
fc_load_weight_U0->m_axi_ddr_V_AWADDR(fc_load_weight_U0_m_axi_ddr_V_AWADDR);
fc_load_weight_U0->m_axi_ddr_V_AWID(fc_load_weight_U0_m_axi_ddr_V_AWID);
fc_load_weight_U0->m_axi_ddr_V_AWLEN(fc_load_weight_U0_m_axi_ddr_V_AWLEN);
fc_load_weight_U0->m_axi_ddr_V_AWSIZE(fc_load_weight_U0_m_axi_ddr_V_AWSIZE);
fc_load_weight_U0->m_axi_ddr_V_AWBURST(fc_load_weight_U0_m_axi_ddr_V_AWBURST);
fc_load_weight_U0->m_axi_ddr_V_AWLOCK(fc_load_weight_U0_m_axi_ddr_V_AWLOCK);
fc_load_weight_U0->m_axi_ddr_V_AWCACHE(fc_load_weight_U0_m_axi_ddr_V_AWCACHE);
fc_load_weight_U0->m_axi_ddr_V_AWPROT(fc_load_weight_U0_m_axi_ddr_V_AWPROT);
fc_load_weight_U0->m_axi_ddr_V_AWQOS(fc_load_weight_U0_m_axi_ddr_V_AWQOS);
fc_load_weight_U0->m_axi_ddr_V_AWREGION(fc_load_weight_U0_m_axi_ddr_V_AWREGION);
fc_load_weight_U0->m_axi_ddr_V_AWUSER(fc_load_weight_U0_m_axi_ddr_V_AWUSER);
fc_load_weight_U0->m_axi_ddr_V_WVALID(fc_load_weight_U0_m_axi_ddr_V_WVALID);
fc_load_weight_U0->m_axi_ddr_V_WREADY(ap_var_for_const0);
fc_load_weight_U0->m_axi_ddr_V_WDATA(fc_load_weight_U0_m_axi_ddr_V_WDATA);
fc_load_weight_U0->m_axi_ddr_V_WSTRB(fc_load_weight_U0_m_axi_ddr_V_WSTRB);
fc_load_weight_U0->m_axi_ddr_V_WLAST(fc_load_weight_U0_m_axi_ddr_V_WLAST);
fc_load_weight_U0->m_axi_ddr_V_WID(fc_load_weight_U0_m_axi_ddr_V_WID);
fc_load_weight_U0->m_axi_ddr_V_WUSER(fc_load_weight_U0_m_axi_ddr_V_WUSER);
fc_load_weight_U0->m_axi_ddr_V_ARVALID(fc_load_weight_U0_m_axi_ddr_V_ARVALID);
fc_load_weight_U0->m_axi_ddr_V_ARREADY(m_axi_ddr_V_ARREADY);
fc_load_weight_U0->m_axi_ddr_V_ARADDR(fc_load_weight_U0_m_axi_ddr_V_ARADDR);
fc_load_weight_U0->m_axi_ddr_V_ARID(fc_load_weight_U0_m_axi_ddr_V_ARID);
fc_load_weight_U0->m_axi_ddr_V_ARLEN(fc_load_weight_U0_m_axi_ddr_V_ARLEN);
fc_load_weight_U0->m_axi_ddr_V_ARSIZE(fc_load_weight_U0_m_axi_ddr_V_ARSIZE);
fc_load_weight_U0->m_axi_ddr_V_ARBURST(fc_load_weight_U0_m_axi_ddr_V_ARBURST);
fc_load_weight_U0->m_axi_ddr_V_ARLOCK(fc_load_weight_U0_m_axi_ddr_V_ARLOCK);
fc_load_weight_U0->m_axi_ddr_V_ARCACHE(fc_load_weight_U0_m_axi_ddr_V_ARCACHE);
fc_load_weight_U0->m_axi_ddr_V_ARPROT(fc_load_weight_U0_m_axi_ddr_V_ARPROT);
fc_load_weight_U0->m_axi_ddr_V_ARQOS(fc_load_weight_U0_m_axi_ddr_V_ARQOS);
fc_load_weight_U0->m_axi_ddr_V_ARREGION(fc_load_weight_U0_m_axi_ddr_V_ARREGION);
fc_load_weight_U0->m_axi_ddr_V_ARUSER(fc_load_weight_U0_m_axi_ddr_V_ARUSER);
fc_load_weight_U0->m_axi_ddr_V_RVALID(m_axi_ddr_V_RVALID);
fc_load_weight_U0->m_axi_ddr_V_RREADY(fc_load_weight_U0_m_axi_ddr_V_RREADY);
fc_load_weight_U0->m_axi_ddr_V_RDATA(m_axi_ddr_V_RDATA);
fc_load_weight_U0->m_axi_ddr_V_RLAST(m_axi_ddr_V_RLAST);
fc_load_weight_U0->m_axi_ddr_V_RID(m_axi_ddr_V_RID);
fc_load_weight_U0->m_axi_ddr_V_RUSER(m_axi_ddr_V_RUSER);
fc_load_weight_U0->m_axi_ddr_V_RRESP(m_axi_ddr_V_RRESP);
fc_load_weight_U0->m_axi_ddr_V_BVALID(ap_var_for_const0);
fc_load_weight_U0->m_axi_ddr_V_BREADY(fc_load_weight_U0_m_axi_ddr_V_BREADY);
fc_load_weight_U0->m_axi_ddr_V_BRESP(ap_var_for_const3);
fc_load_weight_U0->m_axi_ddr_V_BID(ap_var_for_const4);
fc_load_weight_U0->m_axi_ddr_V_BUSER(ap_var_for_const4);
fc_load_weight_U0->och_0(och_0);
fc_load_weight_U0->och_0_out_din(fc_load_weight_U0_och_0_out_din);
fc_load_weight_U0->och_0_out_full_n(och_0_c_full_n);
fc_load_weight_U0->och_0_out_write(fc_load_weight_U0_och_0_out_write);
fc_compute_1_U0 = new fc_compute_1("fc_compute_1_U0");
fc_compute_1_U0->ap_clk(ap_clk);
fc_compute_1_U0->ap_rst(ap_rst);
fc_compute_1_U0->ap_start(fc_compute_1_U0_ap_start);
fc_compute_1_U0->ap_done(fc_compute_1_U0_ap_done);
fc_compute_1_U0->ap_continue(fc_compute_1_U0_ap_continue);
fc_compute_1_U0->ap_idle(fc_compute_1_U0_ap_idle);
fc_compute_1_U0->ap_ready(fc_compute_1_U0_ap_ready);
fc_compute_1_U0->weight_V_address0(fc_compute_1_U0_weight_V_address0);
fc_compute_1_U0->weight_V_ce0(fc_compute_1_U0_weight_V_ce0);
fc_compute_1_U0->weight_V_q0(weight_V_t_q0);
fc_compute_1_U0->input_V_address0(fc_compute_1_U0_input_V_address0);
fc_compute_1_U0->input_V_ce0(fc_compute_1_U0_input_V_ce0);
fc_compute_1_U0->input_V_q0(input_V_q0);
fc_compute_1_U0->bias_address0(fc_compute_1_U0_bias_address0);
fc_compute_1_U0->bias_ce0(fc_compute_1_U0_bias_ce0);
fc_compute_1_U0->bias_q0(bias_q0);
fc_compute_1_U0->scale_address0(fc_compute_1_U0_scale_address0);
fc_compute_1_U0->scale_ce0(fc_compute_1_U0_scale_ce0);
fc_compute_1_U0->scale_q0(scale_q0);
fc_compute_1_U0->output_r_address0(fc_compute_1_U0_output_r_address0);
fc_compute_1_U0->output_r_ce0(fc_compute_1_U0_output_r_ce0);
fc_compute_1_U0->output_r_we0(fc_compute_1_U0_output_r_we0);
fc_compute_1_U0->output_r_d0(fc_compute_1_U0_output_r_d0);
fc_compute_1_U0->och_dout(och_0_c_dout);
fc_compute_1_U0->och_empty_n(och_0_c_empty_n);
fc_compute_1_U0->och_read(fc_compute_1_U0_och_read);
och_0_c_U = new fifo_w10_d2_A("och_0_c_U");
och_0_c_U->clk(ap_clk);
och_0_c_U->reset(ap_rst);
och_0_c_U->if_read_ce(ap_var_for_const2);
och_0_c_U->if_write_ce(ap_var_for_const2);
och_0_c_U->if_din(fc_load_weight_U0_och_0_out_din);
och_0_c_U->if_full_n(och_0_c_full_n);
och_0_c_U->if_write(fc_load_weight_U0_och_0_out_write);
och_0_c_U->if_dout(och_0_c_dout);
och_0_c_U->if_empty_n(och_0_c_empty_n);
och_0_c_U->if_read(fc_compute_1_U0_och_read);
SC_METHOD(thread_ap_channel_done_weight_V);
sensitive << ( fc_load_weight_U0_ap_done );
SC_METHOD(thread_ap_done);
sensitive << ( fc_compute_1_U0_ap_done );
SC_METHOD(thread_ap_idle);
sensitive << ( fc_load_weight_U0_ap_idle );
sensitive << ( fc_compute_1_U0_ap_idle );
sensitive << ( weight_V_t_empty_n );
SC_METHOD(thread_ap_ready);
sensitive << ( fc_load_weight_U0_ap_ready );
SC_METHOD(thread_ap_sync_continue);
sensitive << ( ap_continue );
SC_METHOD(thread_ap_sync_done);
sensitive << ( fc_compute_1_U0_ap_done );
SC_METHOD(thread_ap_sync_ready);
sensitive << ( fc_load_weight_U0_ap_ready );
SC_METHOD(thread_bias_address0);
sensitive << ( fc_compute_1_U0_bias_address0 );
SC_METHOD(thread_bias_address1);
SC_METHOD(thread_bias_ce0);
sensitive << ( fc_compute_1_U0_bias_ce0 );
SC_METHOD(thread_bias_ce1);
SC_METHOD(thread_bias_d0);
SC_METHOD(thread_bias_d1);
SC_METHOD(thread_bias_we0);
SC_METHOD(thread_bias_we1);
SC_METHOD(thread_fc_compute_1_U0_ap_continue);
sensitive << ( ap_continue );
SC_METHOD(thread_fc_compute_1_U0_ap_start);
sensitive << ( weight_V_t_empty_n );
SC_METHOD(thread_fc_compute_1_U0_start_full_n);
SC_METHOD(thread_fc_compute_1_U0_start_write);
SC_METHOD(thread_fc_load_weight_U0_ap_continue);
sensitive << ( weight_V_i_full_n );
SC_METHOD(thread_fc_load_weight_U0_ap_start);
sensitive << ( ap_start );
SC_METHOD(thread_fc_load_weight_U0_start_full_n);
SC_METHOD(thread_fc_load_weight_U0_start_write);
SC_METHOD(thread_fc_load_weight_U0_weight_V_full_n);
sensitive << ( weight_V_i_full_n );
SC_METHOD(thread_input_V_address0);
sensitive << ( fc_compute_1_U0_input_V_address0 );
SC_METHOD(thread_input_V_address1);
SC_METHOD(thread_input_V_ce0);
sensitive << ( fc_compute_1_U0_input_V_ce0 );
SC_METHOD(thread_input_V_ce1);
SC_METHOD(thread_input_V_d0);
SC_METHOD(thread_input_V_d1);
SC_METHOD(thread_input_V_we0);
SC_METHOD(thread_input_V_we1);
SC_METHOD(thread_m_axi_ddr_V_ARADDR);
sensitive << ( fc_load_weight_U0_m_axi_ddr_V_ARADDR );
SC_METHOD(thread_m_axi_ddr_V_ARBURST);
sensitive << ( fc_load_weight_U0_m_axi_ddr_V_ARBURST );
SC_METHOD(thread_m_axi_ddr_V_ARCACHE);
sensitive << ( fc_load_weight_U0_m_axi_ddr_V_ARCACHE );
SC_METHOD(thread_m_axi_ddr_V_ARID);
sensitive << ( fc_load_weight_U0_m_axi_ddr_V_ARID );
SC_METHOD(thread_m_axi_ddr_V_ARLEN);
sensitive << ( fc_load_weight_U0_m_axi_ddr_V_ARLEN );
SC_METHOD(thread_m_axi_ddr_V_ARLOCK);
sensitive << ( fc_load_weight_U0_m_axi_ddr_V_ARLOCK );
SC_METHOD(thread_m_axi_ddr_V_ARPROT);
sensitive << ( fc_load_weight_U0_m_axi_ddr_V_ARPROT );
SC_METHOD(thread_m_axi_ddr_V_ARQOS);
sensitive << ( fc_load_weight_U0_m_axi_ddr_V_ARQOS );
SC_METHOD(thread_m_axi_ddr_V_ARREGION);
sensitive << ( fc_load_weight_U0_m_axi_ddr_V_ARREGION );
SC_METHOD(thread_m_axi_ddr_V_ARSIZE);
sensitive << ( fc_load_weight_U0_m_axi_ddr_V_ARSIZE );
SC_METHOD(thread_m_axi_ddr_V_ARUSER);
sensitive << ( fc_load_weight_U0_m_axi_ddr_V_ARUSER );
SC_METHOD(thread_m_axi_ddr_V_ARVALID);
sensitive << ( fc_load_weight_U0_m_axi_ddr_V_ARVALID );
SC_METHOD(thread_m_axi_ddr_V_AWADDR);
SC_METHOD(thread_m_axi_ddr_V_AWBURST);
SC_METHOD(thread_m_axi_ddr_V_AWCACHE);
SC_METHOD(thread_m_axi_ddr_V_AWID);
SC_METHOD(thread_m_axi_ddr_V_AWLEN);
SC_METHOD(thread_m_axi_ddr_V_AWLOCK);
SC_METHOD(thread_m_axi_ddr_V_AWPROT);
SC_METHOD(thread_m_axi_ddr_V_AWQOS);
SC_METHOD(thread_m_axi_ddr_V_AWREGION);
SC_METHOD(thread_m_axi_ddr_V_AWSIZE);
SC_METHOD(thread_m_axi_ddr_V_AWUSER);
SC_METHOD(thread_m_axi_ddr_V_AWVALID);
SC_METHOD(thread_m_axi_ddr_V_BREADY);
SC_METHOD(thread_m_axi_ddr_V_RREADY);
sensitive << ( fc_load_weight_U0_m_axi_ddr_V_RREADY );
SC_METHOD(thread_m_axi_ddr_V_WDATA);
SC_METHOD(thread_m_axi_ddr_V_WID);
SC_METHOD(thread_m_axi_ddr_V_WLAST);
SC_METHOD(thread_m_axi_ddr_V_WSTRB);
SC_METHOD(thread_m_axi_ddr_V_WUSER);
SC_METHOD(thread_m_axi_ddr_V_WVALID);
SC_METHOD(thread_output_r_address0);
sensitive << ( fc_compute_1_U0_output_r_address0 );
SC_METHOD(thread_output_r_ce0);
sensitive << ( fc_compute_1_U0_output_r_ce0 );
SC_METHOD(thread_output_r_d0);
sensitive << ( fc_compute_1_U0_output_r_d0 );
SC_METHOD(thread_output_r_we0);
sensitive << ( fc_compute_1_U0_output_r_we0 );
SC_METHOD(thread_scale_address0);
sensitive << ( fc_compute_1_U0_scale_address0 );
SC_METHOD(thread_scale_address1);
SC_METHOD(thread_scale_ce0);
sensitive << ( fc_compute_1_U0_scale_ce0 );
SC_METHOD(thread_scale_ce1);
SC_METHOD(thread_scale_d0);
SC_METHOD(thread_scale_d1);
SC_METHOD(thread_scale_we0);
SC_METHOD(thread_scale_we1);
SC_THREAD(thread_ap_var_for_const2);
SC_THREAD(thread_ap_var_for_const0);
SC_THREAD(thread_ap_var_for_const1);
SC_THREAD(thread_ap_var_for_const3);
SC_THREAD(thread_ap_var_for_const4);
static int apTFileNum = 0;
stringstream apTFilenSS;
apTFilenSS << "dataflow_in_loop_sc_trace_" << apTFileNum ++;
string apTFn = apTFilenSS.str();
mVcdFile = sc_create_vcd_trace_file(apTFn.c_str());
mVcdFile->set_time_unit(1, SC_PS);
if (1) {
#ifdef __HLS_TRACE_LEVEL_PORT_HIER__
sc_trace(mVcdFile, ap_clk, "(port)ap_clk");
sc_trace(mVcdFile, ap_rst, "(port)ap_rst");
sc_trace(mVcdFile, m_axi_ddr_V_AWVALID, "(port)m_axi_ddr_V_AWVALID");
sc_trace(mVcdFile, m_axi_ddr_V_AWREADY, "(port)m_axi_ddr_V_AWREADY");
sc_trace(mVcdFile, m_axi_ddr_V_AWADDR, "(port)m_axi_ddr_V_AWADDR");
sc_trace(mVcdFile, m_axi_ddr_V_AWID, "(port)m_axi_ddr_V_AWID");
sc_trace(mVcdFile, m_axi_ddr_V_AWLEN, "(port)m_axi_ddr_V_AWLEN");
sc_trace(mVcdFile, m_axi_ddr_V_AWSIZE, "(port)m_axi_ddr_V_AWSIZE");
sc_trace(mVcdFile, m_axi_ddr_V_AWBURST, "(port)m_axi_ddr_V_AWBURST");
sc_trace(mVcdFile, m_axi_ddr_V_AWLOCK, "(port)m_axi_ddr_V_AWLOCK");
sc_trace(mVcdFile, m_axi_ddr_V_AWCACHE, "(port)m_axi_ddr_V_AWCACHE");
sc_trace(mVcdFile, m_axi_ddr_V_AWPROT, "(port)m_axi_ddr_V_AWPROT");
sc_trace(mVcdFile, m_axi_ddr_V_AWQOS, "(port)m_axi_ddr_V_AWQOS");
sc_trace(mVcdFile, m_axi_ddr_V_AWREGION, "(port)m_axi_ddr_V_AWREGION");
sc_trace(mVcdFile, m_axi_ddr_V_AWUSER, "(port)m_axi_ddr_V_AWUSER");
sc_trace(mVcdFile, m_axi_ddr_V_WVALID, "(port)m_axi_ddr_V_WVALID");
sc_trace(mVcdFile, m_axi_ddr_V_WREADY, "(port)m_axi_ddr_V_WREADY");
sc_trace(mVcdFile, m_axi_ddr_V_WDATA, "(port)m_axi_ddr_V_WDATA");
sc_trace(mVcdFile, m_axi_ddr_V_WSTRB, "(port)m_axi_ddr_V_WSTRB");
sc_trace(mVcdFile, m_axi_ddr_V_WLAST, "(port)m_axi_ddr_V_WLAST");
sc_trace(mVcdFile, m_axi_ddr_V_WID, "(port)m_axi_ddr_V_WID");
sc_trace(mVcdFile, m_axi_ddr_V_WUSER, "(port)m_axi_ddr_V_WUSER");
sc_trace(mVcdFile, m_axi_ddr_V_ARVALID, "(port)m_axi_ddr_V_ARVALID");
sc_trace(mVcdFile, m_axi_ddr_V_ARREADY, "(port)m_axi_ddr_V_ARREADY");
sc_trace(mVcdFile, m_axi_ddr_V_ARADDR, "(port)m_axi_ddr_V_ARADDR");
sc_trace(mVcdFile, m_axi_ddr_V_ARID, "(port)m_axi_ddr_V_ARID");
sc_trace(mVcdFile, m_axi_ddr_V_ARLEN, "(port)m_axi_ddr_V_ARLEN");
sc_trace(mVcdFile, m_axi_ddr_V_ARSIZE, "(port)m_axi_ddr_V_ARSIZE");
sc_trace(mVcdFile, m_axi_ddr_V_ARBURST, "(port)m_axi_ddr_V_ARBURST");
sc_trace(mVcdFile, m_axi_ddr_V_ARLOCK, "(port)m_axi_ddr_V_ARLOCK");
sc_trace(mVcdFile, m_axi_ddr_V_ARCACHE, "(port)m_axi_ddr_V_ARCACHE");
sc_trace(mVcdFile, m_axi_ddr_V_ARPROT, "(port)m_axi_ddr_V_ARPROT");
sc_trace(mVcdFile, m_axi_ddr_V_ARQOS, "(port)m_axi_ddr_V_ARQOS");
sc_trace(mVcdFile, m_axi_ddr_V_ARREGION, "(port)m_axi_ddr_V_ARREGION");
sc_trace(mVcdFile, m_axi_ddr_V_ARUSER, "(port)m_axi_ddr_V_ARUSER");
sc_trace(mVcdFile, m_axi_ddr_V_RVALID, "(port)m_axi_ddr_V_RVALID");
sc_trace(mVcdFile, m_axi_ddr_V_RREADY, "(port)m_axi_ddr_V_RREADY");
sc_trace(mVcdFile, m_axi_ddr_V_RDATA, "(port)m_axi_ddr_V_RDATA");
sc_trace(mVcdFile, m_axi_ddr_V_RLAST, "(port)m_axi_ddr_V_RLAST");
sc_trace(mVcdFile, m_axi_ddr_V_RID, "(port)m_axi_ddr_V_RID");
sc_trace(mVcdFile, m_axi_ddr_V_RUSER, "(port)m_axi_ddr_V_RUSER");
sc_trace(mVcdFile, m_axi_ddr_V_RRESP, "(port)m_axi_ddr_V_RRESP");
sc_trace(mVcdFile, m_axi_ddr_V_BVALID, "(port)m_axi_ddr_V_BVALID");
sc_trace(mVcdFile, m_axi_ddr_V_BREADY, "(port)m_axi_ddr_V_BREADY");
sc_trace(mVcdFile, m_axi_ddr_V_BRESP, "(port)m_axi_ddr_V_BRESP");
sc_trace(mVcdFile, m_axi_ddr_V_BID, "(port)m_axi_ddr_V_BID");
sc_trace(mVcdFile, m_axi_ddr_V_BUSER, "(port)m_axi_ddr_V_BUSER");
sc_trace(mVcdFile, och_0, "(port)och_0");
sc_trace(mVcdFile, input_V_address0, "(port)input_V_address0");
sc_trace(mVcdFile, input_V_ce0, "(port)input_V_ce0");
sc_trace(mVcdFile, input_V_d0, "(port)input_V_d0");
sc_trace(mVcdFile, input_V_q0, "(port)input_V_q0");
sc_trace(mVcdFile, input_V_we0, "(port)input_V_we0");
sc_trace(mVcdFile, input_V_address1, "(port)input_V_address1");
sc_trace(mVcdFile, input_V_ce1, "(port)input_V_ce1");
sc_trace(mVcdFile, input_V_d1, "(port)input_V_d1");
sc_trace(mVcdFile, input_V_q1, "(port)input_V_q1");
sc_trace(mVcdFile, input_V_we1, "(port)input_V_we1");
sc_trace(mVcdFile, bias_address0, "(port)bias_address0");
sc_trace(mVcdFile, bias_ce0, "(port)bias_ce0");
sc_trace(mVcdFile, bias_d0, "(port)bias_d0");
sc_trace(mVcdFile, bias_q0, "(port)bias_q0");
sc_trace(mVcdFile, bias_we0, "(port)bias_we0");
sc_trace(mVcdFile, bias_address1, "(port)bias_address1");
sc_trace(mVcdFile, bias_ce1, "(port)bias_ce1");
sc_trace(mVcdFile, bias_d1, "(port)bias_d1");
sc_trace(mVcdFile, bias_q1, "(port)bias_q1");
sc_trace(mVcdFile, bias_we1, "(port)bias_we1");
sc_trace(mVcdFile, scale_address0, "(port)scale_address0");
sc_trace(mVcdFile, scale_ce0, "(port)scale_ce0");
sc_trace(mVcdFile, scale_d0, "(port)scale_d0");
sc_trace(mVcdFile, scale_q0, "(port)scale_q0");
sc_trace(mVcdFile, scale_we0, "(port)scale_we0");
sc_trace(mVcdFile, scale_address1, "(port)scale_address1");
sc_trace(mVcdFile, scale_ce1, "(port)scale_ce1");
sc_trace(mVcdFile, scale_d1, "(port)scale_d1");
sc_trace(mVcdFile, scale_q1, "(port)scale_q1");
sc_trace(mVcdFile, scale_we1, "(port)scale_we1");
sc_trace(mVcdFile, output_r_address0, "(port)output_r_address0");
sc_trace(mVcdFile, output_r_ce0, "(port)output_r_ce0");
sc_trace(mVcdFile, output_r_d0, "(port)output_r_d0");
sc_trace(mVcdFile, output_r_q0, "(port)output_r_q0");
sc_trace(mVcdFile, output_r_we0, "(port)output_r_we0");
sc_trace(mVcdFile, och_0_ap_vld, "(port)och_0_ap_vld");
sc_trace(mVcdFile, ap_start, "(port)ap_start");
sc_trace(mVcdFile, ap_done, "(port)ap_done");
sc_trace(mVcdFile, ap_ready, "(port)ap_ready");
sc_trace(mVcdFile, ap_idle, "(port)ap_idle");
sc_trace(mVcdFile, ap_continue, "(port)ap_continue");
#endif
#ifdef __HLS_TRACE_LEVEL_INT__
sc_trace(mVcdFile, weight_V_i_q0, "weight_V_i_q0");
sc_trace(mVcdFile, weight_V_t_q0, "weight_V_t_q0");
sc_trace(mVcdFile, fc_load_weight_U0_ap_start, "fc_load_weight_U0_ap_start");
sc_trace(mVcdFile, fc_load_weight_U0_ap_done, "fc_load_weight_U0_ap_done");
sc_trace(mVcdFile, fc_load_weight_U0_ap_continue, "fc_load_weight_U0_ap_continue");
sc_trace(mVcdFile, fc_load_weight_U0_ap_idle, "fc_load_weight_U0_ap_idle");
sc_trace(mVcdFile, fc_load_weight_U0_ap_ready, "fc_load_weight_U0_ap_ready");
sc_trace(mVcdFile, fc_load_weight_U0_weight_V_address0, "fc_load_weight_U0_weight_V_address0");
sc_trace(mVcdFile, fc_load_weight_U0_weight_V_ce0, "fc_load_weight_U0_weight_V_ce0");
sc_trace(mVcdFile, fc_load_weight_U0_weight_V_we0, "fc_load_weight_U0_weight_V_we0");
sc_trace(mVcdFile, fc_load_weight_U0_weight_V_d0, "fc_load_weight_U0_weight_V_d0");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_AWVALID, "fc_load_weight_U0_m_axi_ddr_V_AWVALID");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_AWADDR, "fc_load_weight_U0_m_axi_ddr_V_AWADDR");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_AWID, "fc_load_weight_U0_m_axi_ddr_V_AWID");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_AWLEN, "fc_load_weight_U0_m_axi_ddr_V_AWLEN");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_AWSIZE, "fc_load_weight_U0_m_axi_ddr_V_AWSIZE");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_AWBURST, "fc_load_weight_U0_m_axi_ddr_V_AWBURST");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_AWLOCK, "fc_load_weight_U0_m_axi_ddr_V_AWLOCK");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_AWCACHE, "fc_load_weight_U0_m_axi_ddr_V_AWCACHE");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_AWPROT, "fc_load_weight_U0_m_axi_ddr_V_AWPROT");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_AWQOS, "fc_load_weight_U0_m_axi_ddr_V_AWQOS");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_AWREGION, "fc_load_weight_U0_m_axi_ddr_V_AWREGION");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_AWUSER, "fc_load_weight_U0_m_axi_ddr_V_AWUSER");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_WVALID, "fc_load_weight_U0_m_axi_ddr_V_WVALID");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_WDATA, "fc_load_weight_U0_m_axi_ddr_V_WDATA");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_WSTRB, "fc_load_weight_U0_m_axi_ddr_V_WSTRB");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_WLAST, "fc_load_weight_U0_m_axi_ddr_V_WLAST");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_WID, "fc_load_weight_U0_m_axi_ddr_V_WID");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_WUSER, "fc_load_weight_U0_m_axi_ddr_V_WUSER");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_ARVALID, "fc_load_weight_U0_m_axi_ddr_V_ARVALID");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_ARADDR, "fc_load_weight_U0_m_axi_ddr_V_ARADDR");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_ARID, "fc_load_weight_U0_m_axi_ddr_V_ARID");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_ARLEN, "fc_load_weight_U0_m_axi_ddr_V_ARLEN");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_ARSIZE, "fc_load_weight_U0_m_axi_ddr_V_ARSIZE");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_ARBURST, "fc_load_weight_U0_m_axi_ddr_V_ARBURST");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_ARLOCK, "fc_load_weight_U0_m_axi_ddr_V_ARLOCK");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_ARCACHE, "fc_load_weight_U0_m_axi_ddr_V_ARCACHE");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_ARPROT, "fc_load_weight_U0_m_axi_ddr_V_ARPROT");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_ARQOS, "fc_load_weight_U0_m_axi_ddr_V_ARQOS");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_ARREGION, "fc_load_weight_U0_m_axi_ddr_V_ARREGION");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_ARUSER, "fc_load_weight_U0_m_axi_ddr_V_ARUSER");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_RREADY, "fc_load_weight_U0_m_axi_ddr_V_RREADY");
sc_trace(mVcdFile, fc_load_weight_U0_m_axi_ddr_V_BREADY, "fc_load_weight_U0_m_axi_ddr_V_BREADY");
sc_trace(mVcdFile, fc_load_weight_U0_och_0_out_din, "fc_load_weight_U0_och_0_out_din");
sc_trace(mVcdFile, fc_load_weight_U0_och_0_out_write, "fc_load_weight_U0_och_0_out_write");
sc_trace(mVcdFile, ap_channel_done_weight_V, "ap_channel_done_weight_V");
sc_trace(mVcdFile, fc_load_weight_U0_weight_V_full_n, "fc_load_weight_U0_weight_V_full_n");
sc_trace(mVcdFile, fc_compute_1_U0_ap_start, "fc_compute_1_U0_ap_start");
sc_trace(mVcdFile, fc_compute_1_U0_ap_done, "fc_compute_1_U0_ap_done");
sc_trace(mVcdFile, fc_compute_1_U0_ap_continue, "fc_compute_1_U0_ap_continue");
sc_trace(mVcdFile, fc_compute_1_U0_ap_idle, "fc_compute_1_U0_ap_idle");
sc_trace(mVcdFile, fc_compute_1_U0_ap_ready, "fc_compute_1_U0_ap_ready");
sc_trace(mVcdFile, fc_compute_1_U0_weight_V_address0, "fc_compute_1_U0_weight_V_address0");
sc_trace(mVcdFile, fc_compute_1_U0_weight_V_ce0, "fc_compute_1_U0_weight_V_ce0");
sc_trace(mVcdFile, fc_compute_1_U0_input_V_address0, "fc_compute_1_U0_input_V_address0");
sc_trace(mVcdFile, fc_compute_1_U0_input_V_ce0, "fc_compute_1_U0_input_V_ce0");
sc_trace(mVcdFile, fc_compute_1_U0_bias_address0, "fc_compute_1_U0_bias_address0");
sc_trace(mVcdFile, fc_compute_1_U0_bias_ce0, "fc_compute_1_U0_bias_ce0");
sc_trace(mVcdFile, fc_compute_1_U0_scale_address0, "fc_compute_1_U0_scale_address0");
sc_trace(mVcdFile, fc_compute_1_U0_scale_ce0, "fc_compute_1_U0_scale_ce0");
sc_trace(mVcdFile, fc_compute_1_U0_output_r_address0, "fc_compute_1_U0_output_r_address0");
sc_trace(mVcdFile, fc_compute_1_U0_output_r_ce0, "fc_compute_1_U0_output_r_ce0");
sc_trace(mVcdFile, fc_compute_1_U0_output_r_we0, "fc_compute_1_U0_output_r_we0");
sc_trace(mVcdFile, fc_compute_1_U0_output_r_d0, "fc_compute_1_U0_output_r_d0");
sc_trace(mVcdFile, fc_compute_1_U0_och_read, "fc_compute_1_U0_och_read");
sc_trace(mVcdFile, ap_sync_continue, "ap_sync_continue");
sc_trace(mVcdFile, weight_V_i_full_n, "weight_V_i_full_n");
sc_trace(mVcdFile, weight_V_t_empty_n, "weight_V_t_empty_n");
sc_trace(mVcdFile, och_0_c_full_n, "och_0_c_full_n");
sc_trace(mVcdFile, och_0_c_dout, "och_0_c_dout");
sc_trace(mVcdFile, och_0_c_empty_n, "och_0_c_empty_n");
sc_trace(mVcdFile, ap_sync_done, "ap_sync_done");
sc_trace(mVcdFile, ap_sync_ready, "ap_sync_ready");
sc_trace(mVcdFile, fc_load_weight_U0_start_full_n, "fc_load_weight_U0_start_full_n");
sc_trace(mVcdFile, fc_load_weight_U0_start_write, "fc_load_weight_U0_start_write");
sc_trace(mVcdFile, fc_compute_1_U0_start_full_n, "fc_compute_1_U0_start_full_n");
sc_trace(mVcdFile, fc_compute_1_U0_start_write, "fc_compute_1_U0_start_write");
#endif
}
}
dataflow_in_loop::~dataflow_in_loop() {
if (mVcdFile)
sc_close_vcd_trace_file(mVcdFile);
delete weight_V_U;
delete fc_load_weight_U0;
delete fc_compute_1_U0;
delete och_0_c_U;
}
void dataflow_in_loop::thread_ap_var_for_const2() {
ap_var_for_const2 = ap_const_logic_1;
}
void dataflow_in_loop::thread_ap_var_for_const0() {
ap_var_for_const0 = ap_const_logic_0;
}
void dataflow_in_loop::thread_ap_var_for_const1() {
ap_var_for_const1 = ap_const_lv1024_lc_1;
}
void dataflow_in_loop::thread_ap_var_for_const3() {
ap_var_for_const3 = ap_const_lv2_0;
}
void dataflow_in_loop::thread_ap_var_for_const4() {
ap_var_for_const4 = ap_const_lv1_0;
}
void dataflow_in_loop::thread_ap_channel_done_weight_V() {
ap_channel_done_weight_V = fc_load_weight_U0_ap_done.read();
}
void dataflow_in_loop::thread_ap_done() {
ap_done = fc_compute_1_U0_ap_done.read();
}
void dataflow_in_loop::thread_ap_idle() {
ap_idle = (fc_load_weight_U0_ap_idle.read() & fc_compute_1_U0_ap_idle.read() & (weight_V_t_empty_n.read() ^
ap_const_logic_1));
}
void dataflow_in_loop::thread_ap_ready() {
ap_ready = fc_load_weight_U0_ap_ready.read();
}
void dataflow_in_loop::thread_ap_sync_continue() {
ap_sync_continue = ap_continue.read();
}
void dataflow_in_loop::thread_ap_sync_done() {
ap_sync_done = fc_compute_1_U0_ap_done.read();
}
void dataflow_in_loop::thread_ap_sync_ready() {
ap_sync_ready = fc_load_weight_U0_ap_ready.read();
}
void dataflow_in_loop::thread_bias_address0() {
bias_address0 = fc_compute_1_U0_bias_address0.read();
}
void dataflow_in_loop::thread_bias_address1() {
bias_address1 = ap_const_lv10_0;
}
void dataflow_in_loop::thread_bias_ce0() {
bias_ce0 = fc_compute_1_U0_bias_ce0.read();
}
void dataflow_in_loop::thread_bias_ce1() {
bias_ce1 = ap_const_logic_0;
}
void dataflow_in_loop::thread_bias_d0() {
bias_d0 = ap_const_lv32_0;
}
void dataflow_in_loop::thread_bias_d1() {
bias_d1 = ap_const_lv32_0;
}
void dataflow_in_loop::thread_bias_we0() {
bias_we0 = ap_const_logic_0;
}
void dataflow_in_loop::thread_bias_we1() {
bias_we1 = ap_const_logic_0;
}
void dataflow_in_loop::thread_fc_compute_1_U0_ap_continue() {
fc_compute_1_U0_ap_continue = ap_continue.read();
}
void dataflow_in_loop::thread_fc_compute_1_U0_ap_start() {
fc_compute_1_U0_ap_start = weight_V_t_empty_n.read();
}
void dataflow_in_loop::thread_fc_compute_1_U0_start_full_n() {
fc_compute_1_U0_start_full_n = ap_const_logic_1;
}
void dataflow_in_loop::thread_fc_compute_1_U0_start_write() {
fc_compute_1_U0_start_write = ap_const_logic_0;
}
void dataflow_in_loop::thread_fc_load_weight_U0_ap_continue() {
fc_load_weight_U0_ap_continue = weight_V_i_full_n.read();
}
void dataflow_in_loop::thread_fc_load_weight_U0_ap_start() {
fc_load_weight_U0_ap_start = ap_start.read();
}
void dataflow_in_loop::thread_fc_load_weight_U0_start_full_n() {
fc_load_weight_U0_start_full_n = ap_const_logic_1;
}
void dataflow_in_loop::thread_fc_load_weight_U0_start_write() {
fc_load_weight_U0_start_write = ap_const_logic_0;
}
void dataflow_in_loop::thread_fc_load_weight_U0_weight_V_full_n() {
fc_load_weight_U0_weight_V_full_n = weight_V_i_full_n.read();
}
void dataflow_in_loop::thread_input_V_address0() {
input_V_address0 = fc_compute_1_U0_input_V_address0.read();
}
void dataflow_in_loop::thread_input_V_address1() {
input_V_address1 = ap_const_lv4_0;
}
void dataflow_in_loop::thread_input_V_ce0() {
input_V_ce0 = fc_compute_1_U0_input_V_ce0.read();
}
void dataflow_in_loop::thread_input_V_ce1() {
input_V_ce1 = ap_const_logic_0;
}
void dataflow_in_loop::thread_input_V_d0() {
input_V_d0 = ap_const_lv1024_lc_1;
}
void dataflow_in_loop::thread_input_V_d1() {
input_V_d1 = ap_const_lv1024_lc_1;
}
void dataflow_in_loop::thread_input_V_we0() {
input_V_we0 = ap_const_logic_0;
}
void dataflow_in_loop::thread_input_V_we1() {
input_V_we1 = ap_const_logic_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_ARADDR() {
m_axi_ddr_V_ARADDR = fc_load_weight_U0_m_axi_ddr_V_ARADDR.read();
}
void dataflow_in_loop::thread_m_axi_ddr_V_ARBURST() {
m_axi_ddr_V_ARBURST = fc_load_weight_U0_m_axi_ddr_V_ARBURST.read();
}
void dataflow_in_loop::thread_m_axi_ddr_V_ARCACHE() {
m_axi_ddr_V_ARCACHE = fc_load_weight_U0_m_axi_ddr_V_ARCACHE.read();
}
void dataflow_in_loop::thread_m_axi_ddr_V_ARID() {
m_axi_ddr_V_ARID = fc_load_weight_U0_m_axi_ddr_V_ARID.read();
}
void dataflow_in_loop::thread_m_axi_ddr_V_ARLEN() {
m_axi_ddr_V_ARLEN = fc_load_weight_U0_m_axi_ddr_V_ARLEN.read();
}
void dataflow_in_loop::thread_m_axi_ddr_V_ARLOCK() {
m_axi_ddr_V_ARLOCK = fc_load_weight_U0_m_axi_ddr_V_ARLOCK.read();
}
void dataflow_in_loop::thread_m_axi_ddr_V_ARPROT() {
m_axi_ddr_V_ARPROT = fc_load_weight_U0_m_axi_ddr_V_ARPROT.read();
}
void dataflow_in_loop::thread_m_axi_ddr_V_ARQOS() {
m_axi_ddr_V_ARQOS = fc_load_weight_U0_m_axi_ddr_V_ARQOS.read();
}
void dataflow_in_loop::thread_m_axi_ddr_V_ARREGION() {
m_axi_ddr_V_ARREGION = fc_load_weight_U0_m_axi_ddr_V_ARREGION.read();
}
void dataflow_in_loop::thread_m_axi_ddr_V_ARSIZE() {
m_axi_ddr_V_ARSIZE = fc_load_weight_U0_m_axi_ddr_V_ARSIZE.read();
}
void dataflow_in_loop::thread_m_axi_ddr_V_ARUSER() {
m_axi_ddr_V_ARUSER = fc_load_weight_U0_m_axi_ddr_V_ARUSER.read();
}
void dataflow_in_loop::thread_m_axi_ddr_V_ARVALID() {
m_axi_ddr_V_ARVALID = fc_load_weight_U0_m_axi_ddr_V_ARVALID.read();
}
void dataflow_in_loop::thread_m_axi_ddr_V_AWADDR() {
m_axi_ddr_V_AWADDR = ap_const_lv32_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_AWBURST() {
m_axi_ddr_V_AWBURST = ap_const_lv2_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_AWCACHE() {
m_axi_ddr_V_AWCACHE = ap_const_lv4_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_AWID() {
m_axi_ddr_V_AWID = ap_const_lv1_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_AWLEN() {
m_axi_ddr_V_AWLEN = ap_const_lv32_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_AWLOCK() {
m_axi_ddr_V_AWLOCK = ap_const_lv2_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_AWPROT() {
m_axi_ddr_V_AWPROT = ap_const_lv3_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_AWQOS() {
m_axi_ddr_V_AWQOS = ap_const_lv4_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_AWREGION() {
m_axi_ddr_V_AWREGION = ap_const_lv4_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_AWSIZE() {
m_axi_ddr_V_AWSIZE = ap_const_lv3_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_AWUSER() {
m_axi_ddr_V_AWUSER = ap_const_lv1_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_AWVALID() {
m_axi_ddr_V_AWVALID = ap_const_logic_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_BREADY() {
m_axi_ddr_V_BREADY = ap_const_logic_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_RREADY() {
m_axi_ddr_V_RREADY = fc_load_weight_U0_m_axi_ddr_V_RREADY.read();
}
void dataflow_in_loop::thread_m_axi_ddr_V_WDATA() {
m_axi_ddr_V_WDATA = ap_const_lv128_lc_1;
}
void dataflow_in_loop::thread_m_axi_ddr_V_WID() {
m_axi_ddr_V_WID = ap_const_lv1_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_WLAST() {
m_axi_ddr_V_WLAST = ap_const_logic_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_WSTRB() {
m_axi_ddr_V_WSTRB = ap_const_lv16_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_WUSER() {
m_axi_ddr_V_WUSER = ap_const_lv1_0;
}
void dataflow_in_loop::thread_m_axi_ddr_V_WVALID() {
m_axi_ddr_V_WVALID = ap_const_logic_0;
}
void dataflow_in_loop::thread_output_r_address0() {
output_r_address0 = fc_compute_1_U0_output_r_address0.read();
}
void dataflow_in_loop::thread_output_r_ce0() {
output_r_ce0 = fc_compute_1_U0_output_r_ce0.read();
}
void dataflow_in_loop::thread_output_r_d0() {
output_r_d0 = fc_compute_1_U0_output_r_d0.read();
}
void dataflow_in_loop::thread_output_r_we0() {
output_r_we0 = fc_compute_1_U0_output_r_we0.read();
}
void dataflow_in_loop::thread_scale_address0() {
scale_address0 = fc_compute_1_U0_scale_address0.read();
}
void dataflow_in_loop::thread_scale_address1() {
scale_address1 = ap_const_lv10_0;
}
void dataflow_in_loop::thread_scale_ce0() {
scale_ce0 = fc_compute_1_U0_scale_ce0.read();
}
void dataflow_in_loop::thread_scale_ce1() {
scale_ce1 = ap_const_logic_0;
}
void dataflow_in_loop::thread_scale_d0() {
scale_d0 = ap_const_lv32_0;
}
void dataflow_in_loop::thread_scale_d1() {
scale_d1 = ap_const_lv32_0;
}
void dataflow_in_loop::thread_scale_we0() {
scale_we0 = ap_const_logic_0;
}
void dataflow_in_loop::thread_scale_we1() {
scale_we1 = ap_const_logic_0;
}
}
| [
"yasu@am.ics.keio.ac.jp"
] | yasu@am.ics.keio.ac.jp |
2a46f108bc5e5cbe69f8eb18b33dc7f32c505825 | 35142ada4f02ef34ad47307d3b9770b7c97674b5 | /include/engine/eval.hpp | c8280d0e8756a07de0f5fb480009cc16729d44cb | [] | no_license | BK1603/Wolf-Gang-Engine | 83e58ed1b79b6538dd3493fd7e7fb1ea1f8378e5 | 182c87dbefd3bfd1014f09dd151f4729b7045838 | refs/heads/master | 2020-03-08T16:28:17.659552 | 2018-03-29T03:40:20 | 2018-03-29T03:40:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,505 | hpp | #include <string>
#include <map>
#include <functional>
#include "utility.hpp"
class evaluator
{
std::string expression;
std::map<std::string, double> variables;
std::map<std::string, std::function<double(double)>> functions;
bool is_whitespace(char c)
{
return (
c == ' ' ||
c == '\t' ||
c == '\n' ||
c == '\r'
);
}
bool is_letter(char c)
{
return (
c >= 'a' &&
c <= 'z'
);
}
void skip_whitespace(std::string::iterator& iter)
{
while (iter != expression.end() && is_whitespace(*iter))
++iter;
}
std::string read_name(std::string::iterator& iter)
{
std::string name;
while (iter != expression.end() && is_letter(*iter))
{
name += *iter;
++iter;
}
return std::move(name);
}
double factor(std::string::iterator& iter)
{
skip_whitespace(iter);
// Default at one to avoid divid-by-zero error
double val = 1;
if (iter == expression.end())
return val;
if (*iter == '(')
val = summands(++iter);
else if (*iter == '-')
val = -factor(++iter);
// Function
else if (*iter == '$')
{
auto &func = functions.find(read_name(++iter));
if (func == functions.end())
return 0;
val = func->second(factor(iter));
}
// Variable
else if (is_letter(*iter))
val = variables[read_name(iter)];
// Numeral
else
val = util::to_numeral<double>(expression, iter);
if (iter == expression.end())
return val;
if (*iter == '*')
val *= factor(++iter);
else if (*iter == '/')
val /= factor(++iter);
else if (*iter == '^')
val = std::pow(val, factor(++iter));
return val;
}
double summands(std::string::iterator& iter)
{
double v1 = factor(iter);
while (iter != expression.end())
{
skip_whitespace(iter);
if (*iter == '+')
v1 += factor(++iter);
else if (*iter == '-')
v1 -= factor(++iter);
else if (*iter == ')')
return (++iter, v1);
else
return v1;
}
return v1;
}
public:
void set_expression(const std::string& ex)
{
expression = ex;
}
void set_function(const std::string& name, std::function<double(double)> func)
{
functions[name] = func;
}
double& operator[](const std::string& name)
{
return variables[name];
}
double evaluate()
{
std::string::iterator iter = expression.begin();
return summands(iter);
}
double evaluate(const std::string& ex)
{
set_expression(ex);
return evaluate();
}
static double quick_evaluate(const std::string& ex)
{
evaluator eval;
return eval.evaluate(ex);
}
}; | [
"capnsword@gmail.com"
] | capnsword@gmail.com |
ae2dbea8aa24e30cc2fece02b143d3c125bbc517 | 7487c08a56546157df3f3681b03a7ec5d3bb9c44 | /pgn/mainwindow.cpp | b1281b3e786af00435f740faff8b4b0b07a24392 | [] | no_license | ifanatic/chessgameviewer2 | 431dbdf41474e7d1a2876ba85b431f8827602091 | 90966a7f36f9358666a4a5300f59989389e19d9e | refs/heads/master | 2021-01-22T20:25:49.698309 | 2012-09-13T02:54:30 | 2012-09-13T02:54:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,331 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSqlQuery>
#include <iostream>
#include <sstream>
#include <QSqlRecord>
#include <QMessageBox>
#include <QModelIndexList>
#include <iostream>
#include "ply.h"
#include "fenform.h"
#include <QFileDialog>
#include <QProgressDialog>
#include "pgnimporter.h"
#include "gamefinder.h"
#include "pgnexporter.h"
#include "positionstatdialog.h"
#include "piecepathtracer.h"
#include "piecepathdialog.h"
bool MainWindow::openGame(int id)
{
cout << "opengame: " << endl;
GameFinder finder;
Game game = finder.getGameById(id);
ui->lBlack->setText(game.tags()["Black"].value().c_str());
ui->lWhite->setText(game.tags()["White"].value().c_str());
ui->lWinner->setText(game.tags()["Result"].value().c_str());
vector<pgn::Ply> moves;
ui->lwMoves->clear();
MoveList::iterator moveIter = game.moves().begin();
MoveList::iterator moveIterEnd = game.moves().end();
QString whitePattern = "White: %1";
QString blackPattern = "Black: %1";
while(moveIter != moveIterEnd)
{
ostringstream notation;
if(moveIter->white() != NULL)
{
notation << (*moveIter->white());
ui->lwMoves->addItem(new QListWidgetItem(whitePattern.arg(
notation.str().c_str()), ui->lwMoves));
moves.push_back(*moveIter->white());
}
if(moveIter->black() != NULL)
{
notation.clear();
notation.str("");
notation << (*moveIter->black());
ui->lwMoves->addItem(new QListWidgetItem(blackPattern.arg(
notation.str().c_str()), ui->lwMoves));
moves.push_back(*moveIter->black());
}
++moveIter;
}
_player->setMoves(moves);
_player->goToBegin();
updateViews();
return true;
}
void MainWindow::updateViews()
{
if(_player->getCurrentPos() > 0)
{
ui->lwMoves->item(_player->getCurrentPos())->setSelected(true);
ui->lwMoves->scrollTo(ui->lwMoves->selectionModel()->currentIndex());
}
ui->cbvGame->updateChessboard();
if(_player->getCurrentPos() < 1)
{
ui->pbPrev->setEnabled(false);
}
else
{
ui->pbPrev->setEnabled(true);
}
if(_player->getCurrentPos() == (_player->movesCount() - 1))
{
ui->pbNext->setEnabled(false);
}
else
{
ui->pbNext->setEnabled(true);
}
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->cbvGame, SIGNAL(onPieceClick(int,int)), this, SLOT(onPieceClicked(int,int)));
_gamesModel = new QSqlQueryModel(this);
_gamesModel->setQuery("SELECT * FROM GAMES");
_player = new GamePlayer();
ui->tvGames->setModel(_gamesModel);
ui->tvGames->hideColumn(0);
_isNeedSelectFigure = false;
}
MainWindow::~MainWindow()
{
if(_player != NULL)
{
delete _player;
}
delete ui;
}
void MainWindow::on_pbSearch_clicked()
{
QString pattern = "select * from games where id in (select game_id from moves where "
"fen like '%1')";
pattern = pattern.arg(ui->leSearchString->text().trimmed());
_gamesModel->setQuery(pattern);
}
void MainWindow::on_pbClear_clicked()
{
_gamesModel->setQuery("SELECT * FROM GAMES");
}
void MainWindow::on_pbOpen_clicked()
{
QModelIndexList selRows = ui->tvGames->selectionModel()->selectedRows();
if(selRows.size() == 0)
{
std::cout << "No items selected" << std::endl;
return;
}
QModelIndex selectedElement = selRows.at(0);
QString text = _gamesModel->data(_gamesModel->index(selectedElement.row(), 0)).toString();
if(!openGame(text.toInt()))
{
QMessageBox msg;
msg.setText(QString("Cannot open game #") + text);
msg.exec();
}
else
{
cout << "Open complete" << endl;
ui->cbvGame->setChessboard(&_player->chessBoard());
}
}
void MainWindow::on_pbNext_clicked()
{
_player->next();
updateViews();
}
void MainWindow::on_pbPrev_clicked()
{
_player->prev();
updateViews();
}
void MainWindow::on_pbBegin_clicked()
{
_player->goToBegin();
updateViews();
}
void MainWindow::on_pbEnd_clicked()
{
_player->goToEnd();
updateViews();
}
void MainWindow::on_pbFindPgn_clicked()
{
FENForm fen;
QString fenStr = fen.getFENForm(_player->chessBoard(), _player->currentColor()).c_str();
ui->leSearchString->setText(fenStr);
ui->pbSearch->click();
}
void MainWindow::on_actionImport_PGN_triggered()
{
QFileDialog openFileDialog(this);
openFileDialog.exec();
openFileDialog.setFilter("*.pgn");
if(openFileDialog.result() == QDialog::Accepted)
{
if(openFileDialog.selectedFiles().size() == 0)
{
return;
}
PGNImporter importer;
QProgressDialog progressDialog(QString("Import"), "", 0, 100);
connect(&importer, SIGNAL(onProgress(int)), &progressDialog, SLOT(setValue(int)));
importer.importFromFile(openFileDialog.selectedFiles()[0]);
ui->pbClear->click();
}
}
void MainWindow::on_actionExport_to_PGN_triggered()
{
QFileDialog openFileDialog(this);
openFileDialog.exec();
openFileDialog.setFilter("*.pgn");
if(openFileDialog.result() == QDialog::Accepted)
{
if(openFileDialog.selectedFiles().size() == 0)
{
return;
}
vector<int> ids;
for(int i = 0; i < _gamesModel->rowCount(); ++i)
{
QModelIndex selectedElement = _gamesModel->index(i, 0);
QString text = _gamesModel->data(
_gamesModel->index(selectedElement.row(), 0)).toString();
ids.push_back(text.toInt());
}
PGNExporter exporter;
QProgressDialog progressDialog(QString("Import"), "", 0, 100);
connect(&exporter, SIGNAL(onProgress(int)), &progressDialog, SLOT(setValue(int)));
exporter.exportToFile(ids, openFileDialog.selectedFiles()[0]);
// ui->pbClear->click();
}
}
void MainWindow::on_qpbStatForPos_clicked()
{
PositionStatDialog statDialog(_player->chessBoard(), _player->currentColor(), this);
statDialog.exec();
}
void MainWindow::onPieceClicked(int row, int col)
{
if(_isNeedSelectFigure)
{
PiecePathTracer pathTracer;
vector<ChessPosition> path = pathTracer.path(
_player->getMoves(),
_player->getCurrentPos(),
ChessPosition(row, col));
_isNeedSelectFigure = false;
PiecePathDialog pathDialog(
_player->chessBoard().getPiece(row, col),
path,
this);
pathDialog.exec();
}
}
void MainWindow::on_qlTrackFigure_clicked()
{
_isNeedSelectFigure = true;
}
| [
"nikolay@3divi.com"
] | nikolay@3divi.com |
087b9899ade3c13a5df1dacb930d230b1cc530be | 410e45283cf691f932b07c5fdf18d8d8ac9b57c3 | /net/http/http_network_transaction_unittest.cc | d2d72e5636d5cd9409ebec35582bbffca721e32d | [
"BSD-3-Clause"
] | permissive | yanhuashengdian/chrome_browser | f52a7f533a6b8417e19b85f765f43ea63307a1fb | 972d284a9ffa4b794f659f5acc4116087704394c | refs/heads/master | 2022-12-21T03:43:07.108853 | 2019-04-29T14:20:05 | 2019-04-29T14:20:05 | 184,068,841 | 0 | 2 | BSD-3-Clause | 2022-12-17T17:35:55 | 2019-04-29T12:40:27 | null | UTF-8 | C++ | false | false | 757,316 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/http/http_network_transaction.h"
#include <math.h> // ceil
#include <stdarg.h>
#include <stdint.h>
#include <limits>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/optional.h"
#include "base/run_loop.h"
#include "base/stl_util.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_task_environment.h"
#include "base/test/simple_test_clock.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/test/test_file_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "net/base/auth.h"
#include "net/base/chunked_upload_data_stream.h"
#include "net/base/completion_once_callback.h"
#include "net/base/elements_upload_data_stream.h"
#include "net/base/host_port_pair.h"
#include "net/base/ip_endpoint.h"
#include "net/base/load_timing_info.h"
#include "net/base/load_timing_info_test_util.h"
#include "net/base/net_errors.h"
#include "net/base/privacy_mode.h"
#include "net/base/proxy_delegate.h"
#include "net/base/proxy_server.h"
#include "net/base/request_priority.h"
#include "net/base/test_completion_callback.h"
#include "net/base/test_proxy_delegate.h"
#include "net/base/upload_bytes_element_reader.h"
#include "net/base/upload_file_element_reader.h"
#include "net/cert/cert_status_flags.h"
#include "net/cert/mock_cert_verifier.h"
#include "net/dns/mock_host_resolver.h"
#include "net/http/http_auth_challenge_tokenizer.h"
#include "net/http/http_auth_handler_digest.h"
#include "net/http/http_auth_handler_mock.h"
#include "net/http/http_auth_handler_ntlm.h"
#include "net/http/http_auth_scheme.h"
#include "net/http/http_basic_stream.h"
#include "net/http/http_network_session.h"
#include "net/http/http_network_session_peer.h"
#include "net/http/http_proxy_connect_job.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_response_info.h"
#include "net/http/http_server_properties_impl.h"
#include "net/http/http_stream.h"
#include "net/http/http_stream_factory.h"
#include "net/http/http_transaction_test_util.h"
#include "net/log/net_log.h"
#include "net/log/net_log_event_type.h"
#include "net/log/net_log_source.h"
#include "net/log/test_net_log.h"
#include "net/log/test_net_log_entry.h"
#include "net/log/test_net_log_util.h"
#include "net/proxy_resolution/mock_proxy_resolver.h"
#include "net/proxy_resolution/proxy_config_service_fixed.h"
#include "net/proxy_resolution/proxy_info.h"
#include "net/proxy_resolution/proxy_resolution_service.h"
#include "net/proxy_resolution/proxy_resolver.h"
#include "net/proxy_resolution/proxy_resolver_factory.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/client_socket_pool.h"
#include "net/socket/client_socket_pool_manager.h"
#include "net/socket/connect_job.h"
#include "net/socket/connection_attempts.h"
#include "net/socket/mock_client_socket_pool_manager.h"
#include "net/socket/next_proto.h"
#include "net/socket/socket_tag.h"
#include "net/socket/socket_test_util.h"
#include "net/socket/socks_connect_job.h"
#include "net/socket/ssl_client_socket.h"
#include "net/spdy/spdy_session.h"
#include "net/spdy/spdy_session_pool.h"
#include "net/spdy/spdy_test_util_common.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "net/ssl/ssl_config_service.h"
#include "net/ssl/ssl_info.h"
#include "net/ssl/ssl_private_key.h"
#include "net/test/cert_test_util.h"
#include "net/test/gtest_util.h"
#include "net/test/test_data_directory.h"
#include "net/test/test_with_scoped_task_environment.h"
#include "net/third_party/quiche/src/spdy/core/spdy_framer.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/websockets/websocket_handshake_stream_base.h"
#include "net/websockets/websocket_test_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
#include "url/gurl.h"
#if defined(NTLM_PORTABLE)
#include "base/base64.h"
#include "net/ntlm/ntlm_test_data.h"
#endif
#if BUILDFLAG(ENABLE_REPORTING)
#include "net/network_error_logging/network_error_logging_service.h"
#include "net/network_error_logging/network_error_logging_test_util.h"
#include "net/reporting/reporting_cache.h"
#include "net/reporting/reporting_client.h"
#include "net/reporting/reporting_header_parser.h"
#include "net/reporting/reporting_service.h"
#include "net/reporting/reporting_test_util.h"
#endif // BUILDFLAG(ENABLE_REPORTING)
using net::test::IsError;
using net::test::IsOk;
using base::ASCIIToUTF16;
using testing::AnyOf;
//-----------------------------------------------------------------------------
namespace net {
namespace {
const base::string16 kBar(ASCIIToUTF16("bar"));
const base::string16 kBar2(ASCIIToUTF16("bar2"));
const base::string16 kBar3(ASCIIToUTF16("bar3"));
const base::string16 kBaz(ASCIIToUTF16("baz"));
const base::string16 kFirst(ASCIIToUTF16("first"));
const base::string16 kFoo(ASCIIToUTF16("foo"));
const base::string16 kFoo2(ASCIIToUTF16("foo2"));
const base::string16 kFoo3(ASCIIToUTF16("foo3"));
const base::string16 kFou(ASCIIToUTF16("fou"));
const base::string16 kSecond(ASCIIToUTF16("second"));
const base::string16 kWrongPassword(ASCIIToUTF16("wrongpassword"));
const char kAlternativeServiceHttpHeader[] =
"Alt-Svc: h2=\"mail.example.org:443\"\r\n";
int GetIdleSocketCountInTransportSocketPool(HttpNetworkSession* session) {
return session
->GetSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL,
ProxyServer::Direct())
->IdleSocketCount();
}
bool IsTransportSocketPoolStalled(HttpNetworkSession* session) {
return session
->GetSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL,
ProxyServer::Direct())
->IsStalled();
}
// Takes in a Value created from a NetLogHttpResponseParameter, and returns
// a JSONified list of headers as a single string. Uses single quotes instead
// of double quotes for easier comparison. Returns false on failure.
bool GetHeaders(base::DictionaryValue* params, std::string* headers) {
if (!params)
return false;
base::ListValue* header_list;
if (!params->GetList("headers", &header_list))
return false;
std::string double_quote_headers;
base::JSONWriter::Write(*header_list, &double_quote_headers);
base::ReplaceChars(double_quote_headers, "\"", "'", headers);
return true;
}
// Tests LoadTimingInfo in the case a socket is reused and no PAC script is
// used.
void TestLoadTimingReused(const LoadTimingInfo& load_timing_info) {
EXPECT_TRUE(load_timing_info.socket_reused);
EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
EXPECT_FALSE(load_timing_info.send_start.is_null());
EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
// Set at a higher level.
EXPECT_TRUE(load_timing_info.request_start_time.is_null());
EXPECT_TRUE(load_timing_info.request_start.is_null());
EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
}
// Tests LoadTimingInfo in the case a new socket is used and no PAC script is
// used.
void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
int connect_timing_flags) {
EXPECT_FALSE(load_timing_info.socket_reused);
EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
connect_timing_flags);
EXPECT_LE(load_timing_info.connect_timing.connect_end,
load_timing_info.send_start);
EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
// Set at a higher level.
EXPECT_TRUE(load_timing_info.request_start_time.is_null());
EXPECT_TRUE(load_timing_info.request_start.is_null());
EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
}
// Tests LoadTimingInfo in the case a socket is reused and a PAC script is
// used.
void TestLoadTimingReusedWithPac(const LoadTimingInfo& load_timing_info) {
EXPECT_TRUE(load_timing_info.socket_reused);
EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
EXPECT_FALSE(load_timing_info.proxy_resolve_start.is_null());
EXPECT_LE(load_timing_info.proxy_resolve_start,
load_timing_info.proxy_resolve_end);
EXPECT_LE(load_timing_info.proxy_resolve_end,
load_timing_info.send_start);
EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
// Set at a higher level.
EXPECT_TRUE(load_timing_info.request_start_time.is_null());
EXPECT_TRUE(load_timing_info.request_start.is_null());
EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
}
// Tests LoadTimingInfo in the case a new socket is used and a PAC script is
// used.
void TestLoadTimingNotReusedWithPac(const LoadTimingInfo& load_timing_info,
int connect_timing_flags) {
EXPECT_FALSE(load_timing_info.socket_reused);
EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
EXPECT_FALSE(load_timing_info.proxy_resolve_start.is_null());
EXPECT_LE(load_timing_info.proxy_resolve_start,
load_timing_info.proxy_resolve_end);
EXPECT_LE(load_timing_info.proxy_resolve_end,
load_timing_info.connect_timing.connect_start);
ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
connect_timing_flags);
EXPECT_LE(load_timing_info.connect_timing.connect_end,
load_timing_info.send_start);
EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
// Set at a higher level.
EXPECT_TRUE(load_timing_info.request_start_time.is_null());
EXPECT_TRUE(load_timing_info.request_start.is_null());
EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
}
// ProxyResolver that records URLs passed to it, and that can be told what
// result to return.
class CapturingProxyResolver : public ProxyResolver {
public:
CapturingProxyResolver()
: proxy_server_(ProxyServer::SCHEME_HTTP, HostPortPair("myproxy", 80)) {}
~CapturingProxyResolver() override = default;
int GetProxyForURL(const GURL& url,
ProxyInfo* results,
CompletionOnceCallback callback,
std::unique_ptr<Request>* request,
const NetLogWithSource& net_log) override {
results->UseProxyServer(proxy_server_);
resolved_.push_back(url);
return OK;
}
// Sets whether the resolver should use direct connections, instead of a
// proxy.
void set_proxy_server(ProxyServer proxy_server) {
proxy_server_ = proxy_server;
}
const std::vector<GURL>& resolved() const { return resolved_; }
private:
std::vector<GURL> resolved_;
ProxyServer proxy_server_;
DISALLOW_COPY_AND_ASSIGN(CapturingProxyResolver);
};
class CapturingProxyResolverFactory : public ProxyResolverFactory {
public:
explicit CapturingProxyResolverFactory(CapturingProxyResolver* resolver)
: ProxyResolverFactory(false), resolver_(resolver) {}
int CreateProxyResolver(const scoped_refptr<PacFileData>& pac_script,
std::unique_ptr<ProxyResolver>* resolver,
CompletionOnceCallback callback,
std::unique_ptr<Request>* request) override {
*resolver = std::make_unique<ForwardingProxyResolver>(resolver_);
return OK;
}
private:
ProxyResolver* resolver_;
};
std::unique_ptr<HttpNetworkSession> CreateSession(
SpdySessionDependencies* session_deps) {
return SpdySessionDependencies::SpdyCreateSession(session_deps);
}
class FailingProxyResolverFactory : public ProxyResolverFactory {
public:
FailingProxyResolverFactory() : ProxyResolverFactory(false) {}
// ProxyResolverFactory override.
int CreateProxyResolver(const scoped_refptr<PacFileData>& script_data,
std::unique_ptr<ProxyResolver>* result,
CompletionOnceCallback callback,
std::unique_ptr<Request>* request) override {
return ERR_PAC_SCRIPT_FAILED;
}
};
class TestSSLConfigService : public SSLConfigService {
public:
explicit TestSSLConfigService(const SSLConfig& config) : config_(config) {}
~TestSSLConfigService() override = default;
void GetSSLConfig(SSLConfig* config) override { *config = config_; }
bool CanShareConnectionWithClientCerts(
const std::string& hostname) const override {
return false;
}
private:
SSLConfig config_;
};
} // namespace
class HttpNetworkTransactionTest : public PlatformTest,
public WithScopedTaskEnvironment {
public:
~HttpNetworkTransactionTest() override {
// Important to restore the per-pool limit first, since the pool limit must
// always be greater than group limit, and the tests reduce both limits.
ClientSocketPoolManager::set_max_sockets_per_pool(
HttpNetworkSession::NORMAL_SOCKET_POOL, old_max_pool_sockets_);
ClientSocketPoolManager::set_max_sockets_per_group(
HttpNetworkSession::NORMAL_SOCKET_POOL, old_max_group_sockets_);
}
protected:
HttpNetworkTransactionTest()
: WithScopedTaskEnvironment(
base::test::ScopedTaskEnvironment::MainThreadType::IO_MOCK_TIME,
base::test::ScopedTaskEnvironment::NowSource::
MAIN_THREAD_MOCK_TIME),
dummy_connect_job_params_(
nullptr /* client_socket_factory */,
nullptr /* host_resolver */,
nullptr /* http_auth_cache */,
nullptr /* http_auth_handler_factory */,
nullptr /* spdy_session_pool */,
nullptr /* quic_supported_versions */,
nullptr /* quic_stream_factory */,
nullptr /* proxy_delegate */,
nullptr /* http_user_agent_settings */,
SSLClientSocketContext(),
SSLClientSocketContext(),
nullptr /* socket_performance_watcher_factory */,
nullptr /* network_quality_estimator */,
nullptr /* net_log */,
nullptr /* websocket_endpoint_lock_manager */),
ssl_(ASYNC, OK),
old_max_group_sockets_(ClientSocketPoolManager::max_sockets_per_group(
HttpNetworkSession::NORMAL_SOCKET_POOL)),
old_max_pool_sockets_(ClientSocketPoolManager::max_sockets_per_pool(
HttpNetworkSession::NORMAL_SOCKET_POOL)) {
session_deps_.enable_http2_alternative_service = true;
}
struct SimpleGetHelperResult {
int rv;
std::string status_line;
std::string response_data;
int64_t total_received_bytes;
int64_t total_sent_bytes;
LoadTimingInfo load_timing_info;
ConnectionAttempts connection_attempts;
IPEndPoint remote_endpoint_after_start;
};
void SetUp() override {
NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
base::RunLoop().RunUntilIdle();
// Set an initial delay to ensure that the first call to TimeTicks::Now()
// before incrementing the counter does not return a null value.
FastForwardBy(TimeDelta::FromSeconds(1));
}
void TearDown() override {
NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
base::RunLoop().RunUntilIdle();
// Empty the current queue.
base::RunLoop().RunUntilIdle();
PlatformTest::TearDown();
NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
base::RunLoop().RunUntilIdle();
}
void Check100ResponseTiming(bool use_spdy);
// Either |write_failure| specifies a write failure or |read_failure|
// specifies a read failure when using a reused socket. In either case, the
// failure should cause the network transaction to resend the request, and the
// other argument should be NULL.
void KeepAliveConnectionResendRequestTest(const MockWrite* write_failure,
const MockRead* read_failure);
// Either |write_failure| specifies a write failure or |read_failure|
// specifies a read failure when using a reused socket. In either case, the
// failure should cause the network transaction to resend the request, and the
// other argument should be NULL.
void PreconnectErrorResendRequestTest(const MockWrite* write_failure,
const MockRead* read_failure,
bool use_spdy);
SimpleGetHelperResult SimpleGetHelperForData(
base::span<StaticSocketDataProvider*> providers) {
SimpleGetHelperResult out;
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
for (auto* provider : providers) {
session_deps_.socket_factory->AddSocketDataProvider(provider);
}
TestCompletionCallback callback;
EXPECT_TRUE(log.bound().IsCapturing());
int rv = trans.Start(&request, callback.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
out.rv = callback.WaitForResult();
out.total_received_bytes = trans.GetTotalReceivedBytes();
out.total_sent_bytes = trans.GetTotalSentBytes();
// Even in the failure cases that use this function, connections are always
// successfully established before the error.
EXPECT_TRUE(trans.GetLoadTimingInfo(&out.load_timing_info));
TestLoadTimingNotReused(out.load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
if (out.rv != OK)
return out;
const HttpResponseInfo* response = trans.GetResponseInfo();
// Can't use ASSERT_* inside helper functions like this, so
// return an error.
if (!response || !response->headers) {
out.rv = ERR_UNEXPECTED;
return out;
}
out.status_line = response->headers->GetStatusLine();
EXPECT_EQ("127.0.0.1", response->remote_endpoint.ToStringWithoutPort());
EXPECT_EQ(80, response->remote_endpoint.port());
bool got_endpoint =
trans.GetRemoteEndpoint(&out.remote_endpoint_after_start);
EXPECT_EQ(got_endpoint,
out.remote_endpoint_after_start.address().size() > 0);
rv = ReadTransaction(&trans, &out.response_data);
EXPECT_THAT(rv, IsOk());
TestNetLogEntry::List entries;
log.GetEntries(&entries);
size_t pos = ExpectLogContainsSomewhere(
entries, 0, NetLogEventType::HTTP_TRANSACTION_SEND_REQUEST_HEADERS,
NetLogEventPhase::NONE);
ExpectLogContainsSomewhere(
entries, pos, NetLogEventType::HTTP_TRANSACTION_READ_RESPONSE_HEADERS,
NetLogEventPhase::NONE);
std::string line;
EXPECT_TRUE(entries[pos].GetStringValue("line", &line));
EXPECT_EQ("GET / HTTP/1.1\r\n", line);
HttpRequestHeaders request_headers;
EXPECT_TRUE(trans.GetFullRequestHeaders(&request_headers));
std::string value;
EXPECT_TRUE(request_headers.GetHeader("Host", &value));
EXPECT_EQ("www.example.org", value);
EXPECT_TRUE(request_headers.GetHeader("Connection", &value));
EXPECT_EQ("keep-alive", value);
std::string response_headers;
EXPECT_TRUE(GetHeaders(entries[pos].params.get(), &response_headers));
EXPECT_EQ("['Host: www.example.org','Connection: keep-alive']",
response_headers);
out.total_received_bytes = trans.GetTotalReceivedBytes();
// The total number of sent bytes should not have changed.
EXPECT_EQ(out.total_sent_bytes, trans.GetTotalSentBytes());
trans.GetConnectionAttempts(&out.connection_attempts);
return out;
}
SimpleGetHelperResult SimpleGetHelper(base::span<const MockRead> data_reads) {
MockWrite data_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
StaticSocketDataProvider reads(data_reads, data_writes);
StaticSocketDataProvider* data[] = {&reads};
SimpleGetHelperResult out = SimpleGetHelperForData(data);
EXPECT_EQ(CountWriteBytes(data_writes), out.total_sent_bytes);
return out;
}
void AddSSLSocketData() {
ssl_.next_proto = kProtoHTTP2;
ssl_.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "spdy_pooling.pem");
ASSERT_TRUE(ssl_.ssl_info.cert);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_);
}
void ConnectStatusHelperWithExpectedStatus(const MockRead& status,
int expected_status);
void ConnectStatusHelper(const MockRead& status);
void CheckErrorIsPassedBack(int error, IoMode mode);
const CommonConnectJobParams dummy_connect_job_params_;
// These clocks are defined here, even though they're only used in the
// Reporting tests below, since they need to be destroyed after
// |session_deps_|.
base::SimpleTestClock clock_;
base::SimpleTestTickClock tick_clock_;
SpdyTestUtil spdy_util_;
SpdySessionDependencies session_deps_;
SSLSocketDataProvider ssl_;
// Original socket limits. Some tests set these. Safest to always restore
// them once each test has been run.
int old_max_group_sockets_;
int old_max_pool_sockets_;
};
namespace {
class BeforeHeadersSentHandler {
public:
BeforeHeadersSentHandler()
: observed_before_headers_sent_with_proxy_(false),
observed_before_headers_sent_(false) {}
void OnBeforeHeadersSent(const ProxyInfo& proxy_info,
HttpRequestHeaders* request_headers) {
observed_before_headers_sent_ = true;
if (!proxy_info.is_http() && !proxy_info.is_https() &&
!proxy_info.is_quic()) {
return;
}
observed_before_headers_sent_with_proxy_ = true;
observed_proxy_server_uri_ = proxy_info.proxy_server().ToURI();
}
bool observed_before_headers_sent_with_proxy() const {
return observed_before_headers_sent_with_proxy_;
}
bool observed_before_headers_sent() const {
return observed_before_headers_sent_;
}
std::string observed_proxy_server_uri() const {
return observed_proxy_server_uri_;
}
private:
bool observed_before_headers_sent_with_proxy_;
bool observed_before_headers_sent_;
std::string observed_proxy_server_uri_;
DISALLOW_COPY_AND_ASSIGN(BeforeHeadersSentHandler);
};
// Fill |str| with a long header list that consumes >= |size| bytes.
void FillLargeHeadersString(std::string* str, int size) {
const char row[] =
"SomeHeaderName: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n";
const int sizeof_row = strlen(row);
const int num_rows = static_cast<int>(
ceil(static_cast<float>(size) / sizeof_row));
const int sizeof_data = num_rows * sizeof_row;
DCHECK(sizeof_data >= size);
str->reserve(sizeof_data);
for (int i = 0; i < num_rows; ++i)
str->append(row, sizeof_row);
}
#if defined(NTLM_PORTABLE)
uint64_t MockGetMSTime() {
// Tue, 23 May 2017 20:13:07 +0000
return 131400439870000000;
}
// Alternative functions that eliminate randomness and dependency on the local
// host name so that the generated NTLM messages are reproducible.
void MockGenerateRandom(uint8_t* output, size_t n) {
// This is set to 0xaa because the client challenge for testing in
// [MS-NLMP] Section 4.2.1 is 8 bytes of 0xaa.
memset(output, 0xaa, n);
}
std::string MockGetHostName() {
return ntlm::test::kHostnameAscii;
}
#endif // defined(NTLM_PORTABLE)
class CaptureGroupIdTransportSocketPool : public TransportClientSocketPool {
public:
explicit CaptureGroupIdTransportSocketPool(
const CommonConnectJobParams* common_connect_job_params)
: TransportClientSocketPool(0,
0,
base::TimeDelta(),
ProxyServer::Direct(),
false /* is_for_websockets */,
common_connect_job_params,
nullptr /* ssl_config_service */) {}
const ClientSocketPool::GroupId& last_group_id_received() const {
return last_group_id_;
}
bool socket_requested() const { return socket_requested_; }
int RequestSocket(
const ClientSocketPool::GroupId& group_id,
scoped_refptr<ClientSocketPool::SocketParams> socket_params,
const base::Optional<NetworkTrafficAnnotationTag>& proxy_annotation_tag,
RequestPriority priority,
const SocketTag& socket_tag,
ClientSocketPool::RespectLimits respect_limits,
ClientSocketHandle* handle,
CompletionOnceCallback callback,
const ClientSocketPool::ProxyAuthCallback& proxy_auth_callback,
const NetLogWithSource& net_log) override {
last_group_id_ = group_id;
socket_requested_ = true;
return ERR_IO_PENDING;
}
void CancelRequest(const ClientSocketPool::GroupId& group_id,
ClientSocketHandle* handle,
bool cancel_connect_job) override {}
void ReleaseSocket(const ClientSocketPool::GroupId& group_id,
std::unique_ptr<StreamSocket> socket,
int64_t generation) override {}
void CloseIdleSockets() override {}
void CloseIdleSocketsInGroup(
const ClientSocketPool::GroupId& group_id) override {}
int IdleSocketCount() const override { return 0; }
size_t IdleSocketCountInGroup(
const ClientSocketPool::GroupId& group_id) const override {
return 0;
}
LoadState GetLoadState(const ClientSocketPool::GroupId& group_id,
const ClientSocketHandle* handle) const override {
return LOAD_STATE_IDLE;
}
private:
ClientSocketPool::GroupId last_group_id_;
bool socket_requested_ = false;
};
//-----------------------------------------------------------------------------
// Helper functions for validating that AuthChallengeInfo's are correctly
// configured for common cases.
bool CheckBasicServerAuth(
const base::Optional<AuthChallengeInfo>& auth_challenge) {
if (!auth_challenge)
return false;
EXPECT_FALSE(auth_challenge->is_proxy);
EXPECT_EQ("http://www.example.org", auth_challenge->challenger.Serialize());
EXPECT_EQ("MyRealm1", auth_challenge->realm);
EXPECT_EQ(kBasicAuthScheme, auth_challenge->scheme);
return true;
}
bool CheckBasicProxyAuth(
const base::Optional<AuthChallengeInfo>& auth_challenge) {
if (!auth_challenge)
return false;
EXPECT_TRUE(auth_challenge->is_proxy);
EXPECT_EQ("http://myproxy:70", auth_challenge->challenger.Serialize());
EXPECT_EQ("MyRealm1", auth_challenge->realm);
EXPECT_EQ(kBasicAuthScheme, auth_challenge->scheme);
return true;
}
bool CheckBasicSecureProxyAuth(
const base::Optional<AuthChallengeInfo>& auth_challenge) {
if (!auth_challenge)
return false;
EXPECT_TRUE(auth_challenge->is_proxy);
EXPECT_EQ("https://myproxy:70", auth_challenge->challenger.Serialize());
EXPECT_EQ("MyRealm1", auth_challenge->realm);
EXPECT_EQ(kBasicAuthScheme, auth_challenge->scheme);
return true;
}
bool CheckDigestServerAuth(
const base::Optional<AuthChallengeInfo>& auth_challenge) {
if (!auth_challenge)
return false;
EXPECT_FALSE(auth_challenge->is_proxy);
EXPECT_EQ("http://www.example.org", auth_challenge->challenger.Serialize());
EXPECT_EQ("digestive", auth_challenge->realm);
EXPECT_EQ(kDigestAuthScheme, auth_challenge->scheme);
return true;
}
#if defined(NTLM_PORTABLE)
bool CheckNTLMServerAuth(
const base::Optional<AuthChallengeInfo>& auth_challenge) {
if (!auth_challenge)
return false;
EXPECT_FALSE(auth_challenge->is_proxy);
EXPECT_EQ("https://server", auth_challenge->challenger.Serialize());
EXPECT_EQ(std::string(), auth_challenge->realm);
EXPECT_EQ(kNtlmAuthScheme, auth_challenge->scheme);
return true;
}
bool CheckNTLMProxyAuth(
const base::Optional<AuthChallengeInfo>& auth_challenge) {
if (!auth_challenge)
return false;
EXPECT_TRUE(auth_challenge->is_proxy);
EXPECT_EQ("http://server", auth_challenge->challenger.Serialize());
EXPECT_EQ(std::string(), auth_challenge->realm);
EXPECT_EQ(kNtlmAuthScheme, auth_challenge->scheme);
return true;
}
#endif // defined(NTLM_PORTABLE)
} // namespace
TEST_F(HttpNetworkTransactionTest, Basic) {
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
}
TEST_F(HttpNetworkTransactionTest, SimpleGET) {
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.0 200 OK", out.status_line);
EXPECT_EQ("hello world", out.response_data);
int64_t reads_size = CountReadBytes(data_reads);
EXPECT_EQ(reads_size, out.total_received_bytes);
EXPECT_EQ(0u, out.connection_attempts.size());
EXPECT_FALSE(out.remote_endpoint_after_start.address().empty());
}
// Response with no status line.
TEST_F(HttpNetworkTransactionTest, SimpleGETNoHeaders) {
MockRead data_reads[] = {
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/0.9 200 OK", out.status_line);
EXPECT_EQ("hello world", out.response_data);
int64_t reads_size = CountReadBytes(data_reads);
EXPECT_EQ(reads_size, out.total_received_bytes);
}
// Response with no status line, and a weird port. Should fail by default.
TEST_F(HttpNetworkTransactionTest, SimpleGETNoHeadersWeirdPort) {
MockRead data_reads[] = {
MockRead("hello world"), MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpRequestInfo request;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
request.method = "GET";
request.url = GURL("http://www.example.com:2000/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsError(ERR_INVALID_HTTP_RESPONSE));
}
// Tests that request info can be destroyed after the headers phase is complete.
TEST_F(HttpNetworkTransactionTest, SimpleGETNoReadDestroyRequestInfo) {
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"), MockRead("Connection: keep-alive\r\n"),
MockRead("Content-Length: 100\r\n\r\n"), MockRead(SYNCHRONOUS, 0),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
{
auto request = std::make_unique<HttpRequestInfo>();
request->method = "GET";
request->url = GURL("http://www.example.org/");
request->traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
int rv =
trans->Start(request.get(), callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
} // Let request info be destroyed.
trans.reset();
}
// Response with no status line, and a weird port. Option to allow weird ports
// enabled.
TEST_F(HttpNetworkTransactionTest, SimpleGETNoHeadersWeirdPortAllowed) {
MockRead data_reads[] = {
MockRead("hello world"), MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
session_deps_.http_09_on_non_default_ports_enabled = true;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpRequestInfo request;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
request.method = "GET";
request.url = GURL("http://www.example.com:2000/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* info = trans->GetResponseInfo();
ASSERT_TRUE(info->headers);
EXPECT_EQ("HTTP/0.9 200 OK", info->headers->GetStatusLine());
// Don't bother to read the body - that's verified elsewhere, important thing
// is that the option to allow HTTP/0.9 on non-default ports is respected.
}
// Allow up to 4 bytes of junk to precede status line.
TEST_F(HttpNetworkTransactionTest, StatusLineJunk3Bytes) {
MockRead data_reads[] = {
MockRead("xxxHTTP/1.0 404 Not Found\nServer: blah\n\nDATA"),
MockRead(SYNCHRONOUS, OK),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.0 404 Not Found", out.status_line);
EXPECT_EQ("DATA", out.response_data);
int64_t reads_size = CountReadBytes(data_reads);
EXPECT_EQ(reads_size, out.total_received_bytes);
}
// Allow up to 4 bytes of junk to precede status line.
TEST_F(HttpNetworkTransactionTest, StatusLineJunk4Bytes) {
MockRead data_reads[] = {
MockRead("\n\nQJHTTP/1.0 404 Not Found\nServer: blah\n\nDATA"),
MockRead(SYNCHRONOUS, OK),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.0 404 Not Found", out.status_line);
EXPECT_EQ("DATA", out.response_data);
int64_t reads_size = CountReadBytes(data_reads);
EXPECT_EQ(reads_size, out.total_received_bytes);
}
// Beyond 4 bytes of slop and it should fail to find a status line.
TEST_F(HttpNetworkTransactionTest, StatusLineJunk5Bytes) {
MockRead data_reads[] = {
MockRead("xxxxxHTTP/1.1 404 Not Found\nServer: blah"),
MockRead(SYNCHRONOUS, OK),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/0.9 200 OK", out.status_line);
EXPECT_EQ("xxxxxHTTP/1.1 404 Not Found\nServer: blah", out.response_data);
int64_t reads_size = CountReadBytes(data_reads);
EXPECT_EQ(reads_size, out.total_received_bytes);
}
// Same as StatusLineJunk4Bytes, except the read chunks are smaller.
TEST_F(HttpNetworkTransactionTest, StatusLineJunk4Bytes_Slow) {
MockRead data_reads[] = {
MockRead("\n"),
MockRead("\n"),
MockRead("Q"),
MockRead("J"),
MockRead("HTTP/1.0 404 Not Found\nServer: blah\n\nDATA"),
MockRead(SYNCHRONOUS, OK),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.0 404 Not Found", out.status_line);
EXPECT_EQ("DATA", out.response_data);
int64_t reads_size = CountReadBytes(data_reads);
EXPECT_EQ(reads_size, out.total_received_bytes);
}
// Close the connection before enough bytes to have a status line.
TEST_F(HttpNetworkTransactionTest, StatusLinePartial) {
MockRead data_reads[] = {
MockRead("HTT"),
MockRead(SYNCHRONOUS, OK),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/0.9 200 OK", out.status_line);
EXPECT_EQ("HTT", out.response_data);
int64_t reads_size = CountReadBytes(data_reads);
EXPECT_EQ(reads_size, out.total_received_bytes);
}
// Simulate a 204 response, lacking a Content-Length header, sent over a
// persistent connection. The response should still terminate since a 204
// cannot have a response body.
TEST_F(HttpNetworkTransactionTest, StopsReading204) {
char junk[] = "junk";
MockRead data_reads[] = {
MockRead("HTTP/1.1 204 No Content\r\n\r\n"),
MockRead(junk), // Should not be read!!
MockRead(SYNCHRONOUS, OK),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.1 204 No Content", out.status_line);
EXPECT_EQ("", out.response_data);
int64_t reads_size = CountReadBytes(data_reads);
int64_t response_size = reads_size - strlen(junk);
EXPECT_EQ(response_size, out.total_received_bytes);
}
// A simple request using chunked encoding with some extra data after.
TEST_F(HttpNetworkTransactionTest, ChunkedEncoding) {
std::string final_chunk = "0\r\n\r\n";
std::string extra_data = "HTTP/1.1 200 OK\r\n";
std::string last_read = final_chunk + extra_data;
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"),
MockRead("5\r\nHello\r\n"),
MockRead("1\r\n"),
MockRead(" \r\n"),
MockRead("5\r\nworld\r\n"),
MockRead(last_read.data()),
MockRead(SYNCHRONOUS, OK),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
EXPECT_EQ("Hello world", out.response_data);
int64_t reads_size = CountReadBytes(data_reads);
int64_t response_size = reads_size - extra_data.size();
EXPECT_EQ(response_size, out.total_received_bytes);
}
// Next tests deal with http://crbug.com/56344.
TEST_F(HttpNetworkTransactionTest,
MultipleContentLengthHeadersNoTransferEncoding) {
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 10\r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsError(ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH));
}
TEST_F(HttpNetworkTransactionTest,
DuplicateContentLengthHeadersNoTransferEncoding) {
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 5\r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
MockRead("Hello"),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
EXPECT_EQ("Hello", out.response_data);
}
TEST_F(HttpNetworkTransactionTest,
ComplexContentLengthHeadersNoTransferEncoding) {
// More than 2 dupes.
{
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 5\r\n"),
MockRead("Content-Length: 5\r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
MockRead("Hello"),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
EXPECT_EQ("Hello", out.response_data);
}
// HTTP/1.0
{
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Length: 5\r\n"),
MockRead("Content-Length: 5\r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
MockRead("Hello"),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.0 200 OK", out.status_line);
EXPECT_EQ("Hello", out.response_data);
}
// 2 dupes and one mismatched.
{
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 10\r\n"),
MockRead("Content-Length: 10\r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsError(ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH));
}
}
TEST_F(HttpNetworkTransactionTest,
MultipleContentLengthHeadersTransferEncoding) {
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 666\r\n"),
MockRead("Content-Length: 1337\r\n"),
MockRead("Transfer-Encoding: chunked\r\n\r\n"),
MockRead("5\r\nHello\r\n"),
MockRead("1\r\n"),
MockRead(" \r\n"),
MockRead("5\r\nworld\r\n"),
MockRead("0\r\n\r\nHTTP/1.1 200 OK\r\n"),
MockRead(SYNCHRONOUS, OK),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
EXPECT_EQ("Hello world", out.response_data);
}
// Next tests deal with http://crbug.com/98895.
// Checks that a single Content-Disposition header results in no error.
TEST_F(HttpNetworkTransactionTest, SingleContentDispositionHeader) {
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Disposition: attachment;filename=\"salutations.txt\"r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
MockRead("Hello"),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
EXPECT_EQ("Hello", out.response_data);
}
// Checks that two identical Content-Disposition headers result in no error.
TEST_F(HttpNetworkTransactionTest, TwoIdenticalContentDispositionHeaders) {
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Disposition: attachment;filename=\"greetings.txt\"r\n"),
MockRead("Content-Disposition: attachment;filename=\"greetings.txt\"r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
MockRead("Hello"),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsOk());
EXPECT_EQ("HTTP/1.1 200 OK", out.status_line);
EXPECT_EQ("Hello", out.response_data);
}
// Checks that two distinct Content-Disposition headers result in an error.
TEST_F(HttpNetworkTransactionTest, TwoDistinctContentDispositionHeaders) {
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Disposition: attachment;filename=\"greetings.txt\"r\n"),
MockRead("Content-Disposition: attachment;filename=\"hi.txt\"r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
MockRead("Hello"),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv,
IsError(ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION));
}
// Checks that two identical Location headers result in no error.
// Also tests Location header behavior.
TEST_F(HttpNetworkTransactionTest, TwoIdenticalLocationHeaders) {
MockRead data_reads[] = {
MockRead("HTTP/1.1 302 Redirect\r\n"),
MockRead("Location: http://good.com/\r\n"),
MockRead("Location: http://good.com/\r\n"),
MockRead("Content-Length: 0\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://redirect.com/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 302 Redirect", response->headers->GetStatusLine());
std::string url;
EXPECT_TRUE(response->headers->IsRedirect(&url));
EXPECT_EQ("http://good.com/", url);
EXPECT_TRUE(response->proxy_server.is_direct());
}
// Checks that two distinct Location headers result in an error.
TEST_F(HttpNetworkTransactionTest, TwoDistinctLocationHeaders) {
MockRead data_reads[] = {
MockRead("HTTP/1.1 302 Redirect\r\n"),
MockRead("Location: http://good.com/\r\n"),
MockRead("Location: http://evil.com/\r\n"),
MockRead("Content-Length: 0\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsError(ERR_RESPONSE_HEADERS_MULTIPLE_LOCATION));
}
// Do a request using the HEAD method. Verify that we don't try to read the
// message body (since HEAD has none).
TEST_F(HttpNetworkTransactionTest, Head) {
HttpRequestInfo request;
request.method = "HEAD";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
BeforeHeadersSentHandler headers_handler;
trans.SetBeforeHeadersSentCallback(
base::Bind(&BeforeHeadersSentHandler::OnBeforeHeadersSent,
base::Unretained(&headers_handler)));
MockWrite data_writes1[] = {
MockWrite("HEAD / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 404 Not Found\r\n"), MockRead("Server: Blah\r\n"),
MockRead("Content-Length: 1234\r\n\r\n"),
// No response body because the test stops reading here.
MockRead(SYNCHRONOUS, ERR_UNEXPECTED),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
// Check that the headers got parsed.
EXPECT_TRUE(response->headers);
EXPECT_EQ(1234, response->headers->GetContentLength());
EXPECT_EQ("HTTP/1.1 404 Not Found", response->headers->GetStatusLine());
EXPECT_TRUE(response->proxy_server.is_direct());
EXPECT_TRUE(headers_handler.observed_before_headers_sent());
EXPECT_FALSE(headers_handler.observed_before_headers_sent_with_proxy());
std::string server_header;
size_t iter = 0;
bool has_server_header = response->headers->EnumerateHeader(
&iter, "Server", &server_header);
EXPECT_TRUE(has_server_header);
EXPECT_EQ("Blah", server_header);
// Reading should give EOF right away, since there is no message body
// (despite non-zero content-length).
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("", response_data);
}
TEST_F(HttpNetworkTransactionTest, ReuseConnection) {
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
MockRead("hello"),
MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
MockRead("world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
const char* const kExpectedResponseData[] = {
"hello", "world"
};
for (int i = 0; i < 2; ++i) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
EXPECT_TRUE(response->proxy_server.is_direct());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ(kExpectedResponseData[i], response_data);
}
}
TEST_F(HttpNetworkTransactionTest, Ignores100) {
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(
std::make_unique<UploadBytesElementReader>("foo", 3));
ElementsUploadDataStream upload_data_stream(std::move(element_readers), 0);
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.foo.com/");
request.upload_data_stream = &upload_data_stream;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Check the upload progress returned before initialization is correct.
UploadProgress progress = request.upload_data_stream->GetUploadProgress();
EXPECT_EQ(0u, progress.size());
EXPECT_EQ(0u, progress.position());
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockRead data_reads[] = {
MockRead("HTTP/1.0 100 Continue\r\n\r\n"),
MockRead("HTTP/1.0 200 OK\r\n\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.0 200 OK", response->headers->GetStatusLine());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello world", response_data);
}
// This test is almost the same as Ignores100 above, but the response contains
// a 102 instead of a 100. Also, instead of HTTP/1.0 the response is
// HTTP/1.1 and the two status headers are read in one read.
TEST_F(HttpNetworkTransactionTest, Ignores1xx) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.foo.com/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockRead data_reads[] = {
MockRead("HTTP/1.1 102 Unspecified status code\r\n\r\n"
"HTTP/1.1 200 OK\r\n\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello world", response_data);
}
TEST_F(HttpNetworkTransactionTest, LoadTimingMeasuresTimeToFirstByteForHttp) {
static const base::TimeDelta kDelayAfterFirstByte =
base::TimeDelta::FromMilliseconds(10);
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.foo.com/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::vector<MockWrite> data_writes = {
MockWrite(ASYNC, 0,
"GET / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n\r\n"),
};
std::vector<MockRead> data_reads = {
// Write one byte of the status line, followed by a pause.
MockRead(ASYNC, 1, "H"),
MockRead(ASYNC, ERR_IO_PENDING, 2),
MockRead(ASYNC, 3, "TTP/1.1 200 OK\r\n\r\n"),
MockRead(ASYNC, 4, "hello world"),
MockRead(SYNCHRONOUS, OK, 5),
};
SequencedSocketData data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
data.RunUntilPaused();
ASSERT_TRUE(data.IsPaused());
FastForwardBy(kDelayAfterFirstByte);
data.Resume();
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
EXPECT_FALSE(load_timing_info.receive_headers_start.is_null());
EXPECT_FALSE(load_timing_info.connect_timing.connect_end.is_null());
// Ensure we didn't include the delay in the TTFB time.
EXPECT_EQ(load_timing_info.receive_headers_start,
load_timing_info.connect_timing.connect_end);
// Ensure that the mock clock advanced at all.
EXPECT_EQ(base::TimeTicks::Now() - load_timing_info.receive_headers_start,
kDelayAfterFirstByte);
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello world", response_data);
}
// Tests that the time-to-first-byte reported in a transaction's load timing
// info uses the first response, even if 1XX/informational.
void HttpNetworkTransactionTest::Check100ResponseTiming(bool use_spdy) {
static const base::TimeDelta kDelayAfter100Response =
base::TimeDelta::FromMilliseconds(10);
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.foo.com/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
std::vector<MockWrite> data_writes;
std::vector<MockRead> data_reads;
spdy::SpdySerializedFrame spdy_req(
spdy_util_.ConstructSpdyGet(request.url.spec().c_str(), 1, LOWEST));
spdy::SpdyHeaderBlock spdy_resp1_headers;
spdy_resp1_headers[spdy::kHttp2StatusHeader] = "100";
spdy::SpdySerializedFrame spdy_resp1(
spdy_util_.ConstructSpdyReply(1, spdy_resp1_headers.Clone()));
spdy::SpdySerializedFrame spdy_resp2(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame spdy_data(
spdy_util_.ConstructSpdyDataFrame(1, "hello world", true));
if (use_spdy) {
ssl.next_proto = kProtoHTTP2;
data_writes = {CreateMockWrite(spdy_req, 0)};
data_reads = {
CreateMockRead(spdy_resp1, 1), MockRead(ASYNC, ERR_IO_PENDING, 2),
CreateMockRead(spdy_resp2, 3), CreateMockRead(spdy_data, 4),
MockRead(SYNCHRONOUS, OK, 5),
};
} else {
data_writes = {
MockWrite(ASYNC, 0,
"GET / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n\r\n"),
};
data_reads = {
MockRead(ASYNC, 1, "HTTP/1.1 100 Continue\r\n\r\n"),
MockRead(ASYNC, ERR_IO_PENDING, 2),
MockRead(ASYNC, 3, "HTTP/1.1 200 OK\r\n\r\n"),
MockRead(ASYNC, 4, "hello world"),
MockRead(SYNCHRONOUS, OK, 5),
};
}
SequencedSocketData data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
data.RunUntilPaused();
// We should now have parsed the 100 response and hit ERR_IO_PENDING. Insert
// the delay before parsing the 200 response.
ASSERT_TRUE(data.IsPaused());
FastForwardBy(kDelayAfter100Response);
data.Resume();
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
EXPECT_FALSE(load_timing_info.receive_headers_start.is_null());
EXPECT_FALSE(load_timing_info.connect_timing.connect_end.is_null());
// Ensure we didn't include the delay in the TTFB time.
EXPECT_EQ(load_timing_info.receive_headers_start,
load_timing_info.connect_timing.connect_end);
// Ensure that the mock clock advanced at all.
EXPECT_EQ(base::TimeTicks::Now() - load_timing_info.receive_headers_start,
kDelayAfter100Response);
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello world", response_data);
}
TEST_F(HttpNetworkTransactionTest, MeasuresTimeToFirst100ResponseForHttp) {
Check100ResponseTiming(false /* use_spdy */);
}
TEST_F(HttpNetworkTransactionTest, MeasuresTimeToFirst100ResponseForSpdy) {
Check100ResponseTiming(true /* use_spdy */);
}
TEST_F(HttpNetworkTransactionTest, Incomplete100ThenEOF) {
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.foo.com/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockRead data_reads[] = {
MockRead(SYNCHRONOUS, "HTTP/1.0 100 Continue\r\n"),
MockRead(ASYNC, 0),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("", response_data);
}
TEST_F(HttpNetworkTransactionTest, EmptyResponse) {
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.foo.com/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockRead data_reads[] = {
MockRead(ASYNC, 0),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_EMPTY_RESPONSE));
}
void HttpNetworkTransactionTest::KeepAliveConnectionResendRequestTest(
const MockWrite* write_failure,
const MockRead* read_failure) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.foo.com/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog net_log;
session_deps_.net_log = &net_log;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Written data for successfully sending both requests.
MockWrite data1_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n\r\n")
};
// Read results for the first request.
MockRead data1_reads[] = {
MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
MockRead("hello"),
MockRead(ASYNC, OK),
};
if (write_failure) {
ASSERT_FALSE(read_failure);
data1_writes[1] = *write_failure;
} else {
ASSERT_TRUE(read_failure);
data1_reads[2] = *read_failure;
}
StaticSocketDataProvider data1(data1_reads, data1_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
MockRead data2_reads[] = {
MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
MockRead("world"),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider data2(data2_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data2);
const char* const kExpectedResponseData[] = {
"hello", "world"
};
uint32_t first_socket_log_id = NetLogSource::kInvalidId;
for (int i = 0; i < 2; ++i) {
TestCompletionCallback callback;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
if (i == 0) {
first_socket_log_id = load_timing_info.socket_log_id;
} else {
// The second request should be using a new socket.
EXPECT_NE(first_socket_log_id, load_timing_info.socket_log_id);
}
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
EXPECT_TRUE(response->proxy_server.is_direct());
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ(kExpectedResponseData[i], response_data);
}
}
void HttpNetworkTransactionTest::PreconnectErrorResendRequestTest(
const MockWrite* write_failure,
const MockRead* read_failure,
bool use_spdy) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.foo.com/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog net_log;
session_deps_.net_log = &net_log;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
SSLSocketDataProvider ssl1(ASYNC, OK);
SSLSocketDataProvider ssl2(ASYNC, OK);
if (use_spdy) {
ssl1.next_proto = kProtoHTTP2;
ssl2.next_proto = kProtoHTTP2;
}
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
// SPDY versions of the request and response.
spdy::SpdySerializedFrame spdy_request(spdy_util_.ConstructSpdyGet(
request.url.spec().c_str(), 1, DEFAULT_PRIORITY));
spdy::SpdySerializedFrame spdy_response(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame spdy_data(
spdy_util_.ConstructSpdyDataFrame(1, "hello", true));
// HTTP/1.1 versions of the request and response.
const char kHttpRequest[] = "GET / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n\r\n";
const char kHttpResponse[] = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n";
const char kHttpData[] = "hello";
std::vector<MockRead> data1_reads;
std::vector<MockWrite> data1_writes;
if (write_failure) {
ASSERT_FALSE(read_failure);
data1_writes.push_back(*write_failure);
data1_reads.push_back(MockRead(ASYNC, OK));
} else {
ASSERT_TRUE(read_failure);
if (use_spdy) {
data1_writes.push_back(CreateMockWrite(spdy_request));
} else {
data1_writes.push_back(MockWrite(kHttpRequest));
}
data1_reads.push_back(*read_failure);
}
StaticSocketDataProvider data1(data1_reads, data1_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
std::vector<MockRead> data2_reads;
std::vector<MockWrite> data2_writes;
if (use_spdy) {
data2_writes.push_back(CreateMockWrite(spdy_request, 0, ASYNC));
data2_reads.push_back(CreateMockRead(spdy_response, 1, ASYNC));
data2_reads.push_back(CreateMockRead(spdy_data, 2, ASYNC));
data2_reads.push_back(MockRead(ASYNC, OK, 3));
} else {
data2_writes.push_back(
MockWrite(ASYNC, kHttpRequest, strlen(kHttpRequest), 0));
data2_reads.push_back(
MockRead(ASYNC, kHttpResponse, strlen(kHttpResponse), 1));
data2_reads.push_back(MockRead(ASYNC, kHttpData, strlen(kHttpData), 2));
data2_reads.push_back(MockRead(ASYNC, OK, 3));
}
SequencedSocketData data2(data2_reads, data2_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
// Preconnect a socket.
session->http_stream_factory()->PreconnectStreams(1, request);
// Wait for the preconnect to complete.
// TODO(davidben): Some way to wait for an idle socket count might be handy.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
// Make the request.
TestCompletionCallback callback;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReused(
load_timing_info,
CONNECT_TIMING_HAS_DNS_TIMES|CONNECT_TIMING_HAS_SSL_TIMES);
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
if (response->was_fetched_via_spdy) {
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
} else {
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
}
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ(kHttpData, response_data);
}
// Test that we do not retry indefinitely when a server sends an error like
// ERR_SPDY_PING_FAILED, ERR_SPDY_SERVER_REFUSED_STREAM,
// ERR_QUIC_HANDSHAKE_FAILED or ERR_QUIC_PROTOCOL_ERROR.
TEST_F(HttpNetworkTransactionTest, FiniteRetriesOnIOError) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.foo.com/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Check whether we give up after the third try.
// Construct an HTTP2 request and a "Go away" response.
spdy::SpdySerializedFrame spdy_request(spdy_util_.ConstructSpdyGet(
request.url.spec().c_str(), 1, DEFAULT_PRIORITY));
spdy::SpdySerializedFrame spdy_response_go_away(
spdy_util_.ConstructSpdyGoAway(0));
MockRead data_read1[] = {CreateMockRead(spdy_response_go_away)};
MockWrite data_write[] = {CreateMockWrite(spdy_request, 0)};
// Three go away responses.
StaticSocketDataProvider data1(data_read1, data_write);
StaticSocketDataProvider data2(data_read1, data_write);
StaticSocketDataProvider data3(data_read1, data_write);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
AddSSLSocketData();
session_deps_.socket_factory->AddSocketDataProvider(&data2);
AddSSLSocketData();
session_deps_.socket_factory->AddSocketDataProvider(&data3);
AddSSLSocketData();
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_SPDY_SERVER_REFUSED_STREAM));
}
TEST_F(HttpNetworkTransactionTest, RetryTwiceOnIOError) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.foo.com/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Check whether we try atleast thrice before giving up.
// Construct an HTTP2 request and a "Go away" response.
spdy::SpdySerializedFrame spdy_request(spdy_util_.ConstructSpdyGet(
request.url.spec().c_str(), 1, DEFAULT_PRIORITY));
spdy::SpdySerializedFrame spdy_response_go_away(
spdy_util_.ConstructSpdyGoAway(0));
MockRead data_read1[] = {CreateMockRead(spdy_response_go_away)};
MockWrite data_write[] = {CreateMockWrite(spdy_request, 0)};
// Construct a non error HTTP2 response.
spdy::SpdySerializedFrame spdy_response_no_error(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame spdy_data(
spdy_util_.ConstructSpdyDataFrame(1, true));
MockRead data_read2[] = {CreateMockRead(spdy_response_no_error, 1),
CreateMockRead(spdy_data, 2)};
// Two error responses.
StaticSocketDataProvider data1(data_read1, data_write);
StaticSocketDataProvider data2(data_read1, data_write);
// Followed by a success response.
SequencedSocketData data3(data_read2, data_write);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
AddSSLSocketData();
session_deps_.socket_factory->AddSocketDataProvider(&data2);
AddSSLSocketData();
session_deps_.socket_factory->AddSocketDataProvider(&data3);
AddSSLSocketData();
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
}
TEST_F(HttpNetworkTransactionTest, KeepAliveConnectionNotConnectedOnWrite) {
MockWrite write_failure(ASYNC, ERR_SOCKET_NOT_CONNECTED);
KeepAliveConnectionResendRequestTest(&write_failure, nullptr);
}
TEST_F(HttpNetworkTransactionTest, KeepAliveConnectionReset) {
MockRead read_failure(ASYNC, ERR_CONNECTION_RESET);
KeepAliveConnectionResendRequestTest(nullptr, &read_failure);
}
TEST_F(HttpNetworkTransactionTest, KeepAliveConnectionEOF) {
MockRead read_failure(SYNCHRONOUS, OK); // EOF
KeepAliveConnectionResendRequestTest(nullptr, &read_failure);
}
// Make sure that on a 408 response (Request Timeout), the request is retried,
// if the socket was a reused keep alive socket.
TEST_F(HttpNetworkTransactionTest, KeepAlive408) {
MockRead read_failure(SYNCHRONOUS,
"HTTP/1.1 408 Request Timeout\r\n"
"Connection: Keep-Alive\r\n"
"Content-Length: 6\r\n\r\n"
"Pickle");
KeepAliveConnectionResendRequestTest(nullptr, &read_failure);
}
TEST_F(HttpNetworkTransactionTest, PreconnectErrorNotConnectedOnWrite) {
MockWrite write_failure(ASYNC, ERR_SOCKET_NOT_CONNECTED);
PreconnectErrorResendRequestTest(&write_failure, nullptr, false);
}
TEST_F(HttpNetworkTransactionTest, PreconnectErrorReset) {
MockRead read_failure(ASYNC, ERR_CONNECTION_RESET);
PreconnectErrorResendRequestTest(nullptr, &read_failure, false);
}
TEST_F(HttpNetworkTransactionTest, PreconnectErrorEOF) {
MockRead read_failure(SYNCHRONOUS, OK); // EOF
PreconnectErrorResendRequestTest(nullptr, &read_failure, false);
}
TEST_F(HttpNetworkTransactionTest, PreconnectErrorAsyncEOF) {
MockRead read_failure(ASYNC, OK); // EOF
PreconnectErrorResendRequestTest(nullptr, &read_failure, false);
}
// Make sure that on a 408 response (Request Timeout), the request is retried,
// if the socket was a preconnected (UNUSED_IDLE) socket.
TEST_F(HttpNetworkTransactionTest, RetryOnIdle408) {
MockRead read_failure(SYNCHRONOUS,
"HTTP/1.1 408 Request Timeout\r\n"
"Connection: Keep-Alive\r\n"
"Content-Length: 6\r\n\r\n"
"Pickle");
KeepAliveConnectionResendRequestTest(nullptr, &read_failure);
PreconnectErrorResendRequestTest(nullptr, &read_failure, false);
}
TEST_F(HttpNetworkTransactionTest, SpdyPreconnectErrorNotConnectedOnWrite) {
MockWrite write_failure(ASYNC, ERR_SOCKET_NOT_CONNECTED);
PreconnectErrorResendRequestTest(&write_failure, nullptr, true);
}
TEST_F(HttpNetworkTransactionTest, SpdyPreconnectErrorReset) {
MockRead read_failure(ASYNC, ERR_CONNECTION_RESET);
PreconnectErrorResendRequestTest(nullptr, &read_failure, true);
}
TEST_F(HttpNetworkTransactionTest, SpdyPreconnectErrorEOF) {
MockRead read_failure(SYNCHRONOUS, OK); // EOF
PreconnectErrorResendRequestTest(nullptr, &read_failure, true);
}
TEST_F(HttpNetworkTransactionTest, SpdyPreconnectErrorAsyncEOF) {
MockRead read_failure(ASYNC, OK); // EOF
PreconnectErrorResendRequestTest(nullptr, &read_failure, true);
}
TEST_F(HttpNetworkTransactionTest, NonKeepAliveConnectionReset) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockRead data_reads[] = {
MockRead(ASYNC, ERR_CONNECTION_RESET),
MockRead("HTTP/1.0 200 OK\r\n\r\n"), // Should not be used
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
IPEndPoint endpoint;
EXPECT_TRUE(trans.GetRemoteEndpoint(&endpoint));
EXPECT_LT(0u, endpoint.address().size());
}
// What do various browsers do when the server closes a non-keepalive
// connection without sending any response header or body?
//
// IE7: error page
// Safari 3.1.2 (Windows): error page
// Firefox 3.0.1: blank page
// Opera 9.52: after five attempts, blank page
// Us with WinHTTP: error page (ERR_INVALID_RESPONSE)
// Us: error page (EMPTY_RESPONSE)
TEST_F(HttpNetworkTransactionTest, NonKeepAliveConnectionEOF) {
MockRead data_reads[] = {
MockRead(SYNCHRONOUS, OK), // EOF
MockRead("HTTP/1.0 200 OK\r\n\r\n"), // Should not be used
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
SimpleGetHelperResult out = SimpleGetHelper(data_reads);
EXPECT_THAT(out.rv, IsError(ERR_EMPTY_RESPONSE));
}
// Next 2 cases (KeepAliveEarlyClose and KeepAliveEarlyClose2) are regression
// tests. There was a bug causing HttpNetworkTransaction to hang in the
// destructor in such situations.
// See http://crbug.com/154712 and http://crbug.com/156609.
TEST_F(HttpNetworkTransactionTest, KeepAliveEarlyClose) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Connection: keep-alive\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead("hello"),
MockRead(SYNCHRONOUS, 0),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
scoped_refptr<IOBufferWithSize> io_buf =
base::MakeRefCounted<IOBufferWithSize>(100);
rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
if (rv == ERR_IO_PENDING)
rv = callback.WaitForResult();
EXPECT_EQ(5, rv);
rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
EXPECT_THAT(rv, IsError(ERR_CONTENT_LENGTH_MISMATCH));
trans.reset();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
}
TEST_F(HttpNetworkTransactionTest, KeepAliveEarlyClose2) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Connection: keep-alive\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, 0),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
scoped_refptr<IOBufferWithSize> io_buf(
base::MakeRefCounted<IOBufferWithSize>(100));
rv = trans->Read(io_buf.get(), io_buf->size(), callback.callback());
if (rv == ERR_IO_PENDING)
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_CONTENT_LENGTH_MISMATCH));
trans.reset();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
}
// Test that we correctly reuse a keep-alive connection after not explicitly
// reading the body.
TEST_F(HttpNetworkTransactionTest, KeepAliveAfterUnreadBody) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.foo.com/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog net_log;
session_deps_.net_log = &net_log;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
const char* request_data =
"GET / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n\r\n";
MockWrite data_writes[] = {
MockWrite(ASYNC, 0, request_data), MockWrite(ASYNC, 2, request_data),
MockWrite(ASYNC, 4, request_data), MockWrite(ASYNC, 6, request_data),
MockWrite(ASYNC, 8, request_data), MockWrite(ASYNC, 10, request_data),
MockWrite(ASYNC, 12, request_data), MockWrite(ASYNC, 14, request_data),
MockWrite(ASYNC, 17, request_data), MockWrite(ASYNC, 20, request_data),
};
// Note that because all these reads happen in the same
// StaticSocketDataProvider, it shows that the same socket is being reused for
// all transactions.
MockRead data_reads[] = {
MockRead(ASYNC, 1, "HTTP/1.1 204 No Content\r\n\r\n"),
MockRead(ASYNC, 3, "HTTP/1.1 205 Reset Content\r\n\r\n"),
MockRead(ASYNC, 5, "HTTP/1.1 304 Not Modified\r\n\r\n"),
MockRead(ASYNC, 7,
"HTTP/1.1 302 Found\r\n"
"Content-Length: 0\r\n\r\n"),
MockRead(ASYNC, 9,
"HTTP/1.1 302 Found\r\n"
"Content-Length: 5\r\n\r\n"
"hello"),
MockRead(ASYNC, 11,
"HTTP/1.1 301 Moved Permanently\r\n"
"Content-Length: 0\r\n\r\n"),
MockRead(ASYNC, 13,
"HTTP/1.1 301 Moved Permanently\r\n"
"Content-Length: 5\r\n\r\n"
"hello"),
// In the next two rounds, IsConnectedAndIdle returns false, due to
// the set_busy_before_sync_reads(true) call, while the
// HttpNetworkTransaction is being shut down, but the socket is still
// reuseable. See http://crbug.com/544255.
MockRead(ASYNC, 15,
"HTTP/1.1 200 Hunky-Dory\r\n"
"Content-Length: 5\r\n\r\n"),
MockRead(SYNCHRONOUS, 16, "hello"),
MockRead(ASYNC, 18,
"HTTP/1.1 200 Hunky-Dory\r\n"
"Content-Length: 5\r\n\r\n"
"he"),
MockRead(SYNCHRONOUS, 19, "llo"),
// The body of the final request is actually read.
MockRead(ASYNC, 21, "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
MockRead(ASYNC, 22, "hello"),
};
SequencedSocketData data(data_reads, data_writes);
data.set_busy_before_sync_reads(true);
session_deps_.socket_factory->AddSocketDataProvider(&data);
const int kNumUnreadBodies = base::size(data_writes) - 1;
std::string response_lines[kNumUnreadBodies];
uint32_t first_socket_log_id = NetLogSource::kInvalidId;
for (size_t i = 0; i < kNumUnreadBodies; ++i) {
TestCompletionCallback callback;
auto trans = std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY,
session.get());
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
if (i == 0) {
TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
first_socket_log_id = load_timing_info.socket_log_id;
} else {
TestLoadTimingReused(load_timing_info);
EXPECT_EQ(first_socket_log_id, load_timing_info.socket_log_id);
}
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
response_lines[i] = response->headers->GetStatusLine();
// Delete the transaction without reading the response bodies. Then spin
// the message loop, so the response bodies are drained.
trans.reset();
base::RunLoop().RunUntilIdle();
}
const char* const kStatusLines[] = {
"HTTP/1.1 204 No Content",
"HTTP/1.1 205 Reset Content",
"HTTP/1.1 304 Not Modified",
"HTTP/1.1 302 Found",
"HTTP/1.1 302 Found",
"HTTP/1.1 301 Moved Permanently",
"HTTP/1.1 301 Moved Permanently",
"HTTP/1.1 200 Hunky-Dory",
"HTTP/1.1 200 Hunky-Dory",
};
static_assert(kNumUnreadBodies == base::size(kStatusLines),
"forgot to update kStatusLines");
for (int i = 0; i < kNumUnreadBodies; ++i)
EXPECT_EQ(kStatusLines[i], response_lines[i]);
TestCompletionCallback callback;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello", response_data);
}
// Sockets that receive extra data after a response is complete should not be
// reused.
TEST_F(HttpNetworkTransactionTest, KeepAliveWithUnusedData1) {
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
MockWrite data_writes1[] = {
MockWrite("HEAD / HTTP/1.1\r\n"
"Host: www.borked.com\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 22\r\n\r\n"
"This server is borked."),
};
MockWrite data_writes2[] = {
MockWrite("GET /foo HTTP/1.1\r\n"
"Host: www.borked.com\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads2[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 3\r\n\r\n"
"foo"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
TestCompletionCallback callback;
HttpRequestInfo request1;
request1.method = "HEAD";
request1.url = GURL("http://www.borked.com/");
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
auto trans1 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans1->Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response1 = trans1->GetResponseInfo();
ASSERT_TRUE(response1);
ASSERT_TRUE(response1->headers);
EXPECT_EQ(200, response1->headers->response_code());
EXPECT_TRUE(response1->headers->IsKeepAlive());
std::string response_data1;
EXPECT_THAT(ReadTransaction(trans1.get(), &response_data1), IsOk());
EXPECT_EQ("", response_data1);
// Deleting the transaction attempts to release the socket back into the
// socket pool.
trans1.reset();
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("http://www.borked.com/foo");
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
auto trans2 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
rv = trans2->Start(&request2, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response2 = trans2->GetResponseInfo();
ASSERT_TRUE(response2);
ASSERT_TRUE(response2->headers);
EXPECT_EQ(200, response2->headers->response_code());
std::string response_data2;
EXPECT_THAT(ReadTransaction(trans2.get(), &response_data2), IsOk());
EXPECT_EQ("foo", response_data2);
}
TEST_F(HttpNetworkTransactionTest, KeepAliveWithUnusedData2) {
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
MockWrite data_writes1[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.borked.com\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 22\r\n\r\n"
"This server is borked."
"Bonus data!"),
};
MockWrite data_writes2[] = {
MockWrite("GET /foo HTTP/1.1\r\n"
"Host: www.borked.com\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads2[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 3\r\n\r\n"
"foo"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
TestCompletionCallback callback;
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("http://www.borked.com/");
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
auto trans1 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans1->Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response1 = trans1->GetResponseInfo();
ASSERT_TRUE(response1);
ASSERT_TRUE(response1->headers);
EXPECT_EQ(200, response1->headers->response_code());
EXPECT_TRUE(response1->headers->IsKeepAlive());
std::string response_data1;
EXPECT_THAT(ReadTransaction(trans1.get(), &response_data1), IsOk());
EXPECT_EQ("This server is borked.", response_data1);
// Deleting the transaction attempts to release the socket back into the
// socket pool.
trans1.reset();
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("http://www.borked.com/foo");
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
auto trans2 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
rv = trans2->Start(&request2, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response2 = trans2->GetResponseInfo();
ASSERT_TRUE(response2);
ASSERT_TRUE(response2->headers);
EXPECT_EQ(200, response2->headers->response_code());
std::string response_data2;
EXPECT_THAT(ReadTransaction(trans2.get(), &response_data2), IsOk());
EXPECT_EQ("foo", response_data2);
}
TEST_F(HttpNetworkTransactionTest, KeepAliveWithUnusedData3) {
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
MockWrite data_writes1[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.borked.com\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Connection: keep-alive\r\n"
"Transfer-Encoding: chunked\r\n\r\n"),
MockRead("16\r\nThis server is borked.\r\n"),
MockRead("0\r\n\r\nBonus data!"),
};
MockWrite data_writes2[] = {
MockWrite("GET /foo HTTP/1.1\r\n"
"Host: www.borked.com\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads2[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 3\r\n\r\n"
"foo"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
TestCompletionCallback callback;
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("http://www.borked.com/");
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
auto trans1 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans1->Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response1 = trans1->GetResponseInfo();
ASSERT_TRUE(response1);
ASSERT_TRUE(response1->headers);
EXPECT_EQ(200, response1->headers->response_code());
EXPECT_TRUE(response1->headers->IsKeepAlive());
std::string response_data1;
EXPECT_THAT(ReadTransaction(trans1.get(), &response_data1), IsOk());
EXPECT_EQ("This server is borked.", response_data1);
// Deleting the transaction attempts to release the socket back into the
// socket pool.
trans1.reset();
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("http://www.borked.com/foo");
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
auto trans2 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
rv = trans2->Start(&request2, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response2 = trans2->GetResponseInfo();
ASSERT_TRUE(response2);
ASSERT_TRUE(response2->headers);
EXPECT_EQ(200, response2->headers->response_code());
std::string response_data2;
EXPECT_THAT(ReadTransaction(trans2.get(), &response_data2), IsOk());
EXPECT_EQ("foo", response_data2);
}
// This is a little different from the others - it tests the case that the
// HttpStreamParser doesn't know if there's extra data on a socket or not when
// the HttpNetworkTransaction is torn down, because the response body hasn't
// been read from yet, but the request goes through the HttpResponseBodyDrainer.
TEST_F(HttpNetworkTransactionTest, KeepAliveWithUnusedData4) {
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
MockWrite data_writes1[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.borked.com\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Connection: keep-alive\r\n"
"Transfer-Encoding: chunked\r\n\r\n"),
MockRead("16\r\nThis server is borked.\r\n"),
MockRead("0\r\n\r\nBonus data!"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
TestCompletionCallback callback;
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("http://www.borked.com/");
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response1 = trans->GetResponseInfo();
ASSERT_TRUE(response1);
ASSERT_TRUE(response1->headers);
EXPECT_EQ(200, response1->headers->response_code());
EXPECT_TRUE(response1->headers->IsKeepAlive());
// Deleting the transaction creates an HttpResponseBodyDrainer to read the
// response body.
trans.reset();
// Let the HttpResponseBodyDrainer drain the socket. It should determine the
// socket can't be reused, rather than returning it to the socket pool.
base::RunLoop().RunUntilIdle();
// There should be no idle sockets in the pool.
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
}
// Test the request-challenge-retry sequence for basic auth.
// (basic auth is the easiest to mock, because it has no randomness).
TEST_F(HttpNetworkTransactionTest, BasicAuth) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog log;
session_deps_.net_log = &log;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes1[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
// Give a couple authenticate options (only the middle one is actually
// supported).
MockRead("WWW-Authenticate: Basic invalid\r\n"), // Malformed.
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("WWW-Authenticate: UNSUPPORTED realm=\"FOO\"\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
// Large content-length -- won't matter, as connection will be reset.
MockRead("Content-Length: 10000\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED),
};
// After calling trans->RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite data_writes2[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
// Lastly, the server responds with the actual content.
MockRead data_reads2[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
LoadTimingInfo load_timing_info1;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info1));
TestLoadTimingNotReused(load_timing_info1, CONNECT_TIMING_HAS_DNS_TIMES);
int64_t writes_size1 = CountWriteBytes(data_writes1);
EXPECT_EQ(writes_size1, trans.GetTotalSentBytes());
int64_t reads_size1 = CountReadBytes(data_reads1);
EXPECT_EQ(reads_size1, trans.GetTotalReceivedBytes());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge));
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBar), callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
LoadTimingInfo load_timing_info2;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info2));
TestLoadTimingNotReused(load_timing_info2, CONNECT_TIMING_HAS_DNS_TIMES);
// The load timing after restart should have a new socket ID, and times after
// those of the first load timing.
EXPECT_LE(load_timing_info1.receive_headers_end,
load_timing_info2.connect_timing.connect_start);
EXPECT_NE(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
int64_t writes_size2 = CountWriteBytes(data_writes2);
EXPECT_EQ(writes_size1 + writes_size2, trans.GetTotalSentBytes());
int64_t reads_size2 = CountReadBytes(data_reads2);
EXPECT_EQ(reads_size1 + reads_size2, trans.GetTotalReceivedBytes());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(100, response->headers->GetContentLength());
}
// Test the request-challenge-retry sequence for basic auth.
// (basic auth is the easiest to mock, because it has no randomness).
TEST_F(HttpNetworkTransactionTest, BasicAuthWithAddressChange) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog log;
MockHostResolver* resolver = new MockHostResolver();
session_deps_.net_log = &log;
session_deps_.host_resolver.reset(resolver);
std::unique_ptr<HttpNetworkSession> session = CreateSession(&session_deps_);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
resolver->rules()->ClearRules();
resolver->rules()->AddRule("www.example.org", "127.0.0.1");
MockWrite data_writes1[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
// Give a couple authenticate options (only the middle one is actually
// supported).
MockRead("WWW-Authenticate: Basic invalid\r\n"), // Malformed.
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("WWW-Authenticate: UNSUPPORTED realm=\"FOO\"\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
// Large content-length -- won't matter, as connection will be reset.
MockRead("Content-Length: 10000\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED),
};
// After calling trans->RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite data_writes2[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
// Lastly, the server responds with the actual content.
MockRead data_reads2[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"), MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
TestCompletionCallback callback1;
EXPECT_EQ(OK, callback1.GetResult(trans.Start(&request, callback1.callback(),
NetLogWithSource())));
LoadTimingInfo load_timing_info1;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info1));
TestLoadTimingNotReused(load_timing_info1, CONNECT_TIMING_HAS_DNS_TIMES);
int64_t writes_size1 = CountWriteBytes(data_writes1);
EXPECT_EQ(writes_size1, trans.GetTotalSentBytes());
int64_t reads_size1 = CountReadBytes(data_reads1);
EXPECT_EQ(reads_size1, trans.GetTotalReceivedBytes());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge));
IPEndPoint endpoint;
EXPECT_TRUE(trans.GetRemoteEndpoint(&endpoint));
ASSERT_FALSE(endpoint.address().empty());
EXPECT_EQ("127.0.0.1:80", endpoint.ToString());
resolver->rules()->ClearRules();
resolver->rules()->AddRule("www.example.org", "127.0.0.2");
TestCompletionCallback callback2;
EXPECT_EQ(OK, callback2.GetResult(trans.RestartWithAuth(
AuthCredentials(kFoo, kBar), callback2.callback())));
LoadTimingInfo load_timing_info2;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info2));
TestLoadTimingNotReused(load_timing_info2, CONNECT_TIMING_HAS_DNS_TIMES);
// The load timing after restart should have a new socket ID, and times after
// those of the first load timing.
EXPECT_LE(load_timing_info1.receive_headers_end,
load_timing_info2.connect_timing.connect_start);
EXPECT_NE(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
int64_t writes_size2 = CountWriteBytes(data_writes2);
EXPECT_EQ(writes_size1 + writes_size2, trans.GetTotalSentBytes());
int64_t reads_size2 = CountReadBytes(data_reads2);
EXPECT_EQ(reads_size1 + reads_size2, trans.GetTotalReceivedBytes());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(100, response->headers->GetContentLength());
EXPECT_TRUE(trans.GetRemoteEndpoint(&endpoint));
ASSERT_FALSE(endpoint.address().empty());
EXPECT_EQ("127.0.0.2:80", endpoint.ToString());
}
// Test that, if the server requests auth indefinitely, HttpNetworkTransaction
// will eventually give up.
TEST_F(HttpNetworkTransactionTest, BasicAuthForever) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog log;
session_deps_.net_log = &log;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
// Give a couple authenticate options (only the middle one is actually
// supported).
MockRead("WWW-Authenticate: Basic invalid\r\n"), // Malformed.
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("WWW-Authenticate: UNSUPPORTED realm=\"FOO\"\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
// Large content-length -- won't matter, as connection will be reset.
MockRead("Content-Length: 10000\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED),
};
// After calling trans->RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite data_writes_restart[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = callback.GetResult(
trans.Start(&request, callback.callback(), NetLogWithSource()));
std::vector<std::unique_ptr<StaticSocketDataProvider>> data_restarts;
for (int i = 0; i < 32; i++) {
// Check the previous response was a 401.
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge));
data_restarts.push_back(std::make_unique<StaticSocketDataProvider>(
data_reads, data_writes_restart));
session_deps_.socket_factory->AddSocketDataProvider(
data_restarts.back().get());
rv = callback.GetResult(trans.RestartWithAuth(AuthCredentials(kFoo, kBar),
callback.callback()));
}
// After too many tries, the transaction should have given up.
EXPECT_THAT(rv, IsError(ERR_TOO_MANY_RETRIES));
}
TEST_F(HttpNetworkTransactionTest, DoNotSendAuth) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
// Large content-length -- won't matter, as connection will be reset.
MockRead("Content-Length: 10000\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_EQ(0, rv);
int64_t writes_size = CountWriteBytes(data_writes);
EXPECT_EQ(writes_size, trans.GetTotalSentBytes());
int64_t reads_size = CountReadBytes(data_reads);
EXPECT_EQ(reads_size, trans.GetTotalReceivedBytes());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
}
// Test the request-challenge-retry sequence for basic auth, over a keep-alive
// connection.
TEST_F(HttpNetworkTransactionTest, BasicAuthKeepAlive) {
// On the second pass, the body read of the auth challenge is synchronous, so
// IsConnectedAndIdle returns false. The socket should still be drained and
// reused. See http://crbug.com/544255.
for (int i = 0; i < 2; ++i) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog log;
session_deps_.net_log = &log;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
MockWrite data_writes[] = {
MockWrite(ASYNC, 0,
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
// After calling trans.RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite(ASYNC, 6,
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead(ASYNC, 1, "HTTP/1.1 401 Unauthorized\r\n"),
MockRead(ASYNC, 2, "WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead(ASYNC, 3, "Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead(ASYNC, 4, "Content-Length: 14\r\n\r\n"),
MockRead(i == 0 ? ASYNC : SYNCHRONOUS, 5, "Unauthorized\r\n"),
// Lastly, the server responds with the actual content.
MockRead(ASYNC, 7, "HTTP/1.1 200 OK\r\n"),
MockRead(ASYNC, 8, "Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead(ASYNC, 9, "Content-Length: 5\r\n\r\n"),
MockRead(ASYNC, 10, "Hello"),
};
SequencedSocketData data(data_reads, data_writes);
data.set_busy_before_sync_reads(true);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
ASSERT_THAT(callback1.GetResult(rv), IsOk());
LoadTimingInfo load_timing_info1;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info1));
TestLoadTimingNotReused(load_timing_info1, CONNECT_TIMING_HAS_DNS_TIMES);
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge));
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBar),
callback2.callback());
ASSERT_THAT(callback2.GetResult(rv), IsOk());
LoadTimingInfo load_timing_info2;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info2));
TestLoadTimingReused(load_timing_info2);
// The load timing after restart should have the same socket ID, and times
// those of the first load timing.
EXPECT_LE(load_timing_info1.receive_headers_end,
load_timing_info2.send_start);
EXPECT_EQ(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(5, response->headers->GetContentLength());
std::string response_data;
EXPECT_THAT(ReadTransaction(&trans, &response_data), IsOk());
int64_t writes_size = CountWriteBytes(data_writes);
EXPECT_EQ(writes_size, trans.GetTotalSentBytes());
int64_t reads_size = CountReadBytes(data_reads);
EXPECT_EQ(reads_size, trans.GetTotalReceivedBytes());
}
}
// Test the request-challenge-retry sequence for basic auth, over a keep-alive
// connection and with no response body to drain.
TEST_F(HttpNetworkTransactionTest, BasicAuthKeepAliveNoBody) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
MockWrite data_writes1[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
// After calling trans.RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 401 Unauthorized\r\n"),
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Length: 0\r\n\r\n"), // No response body.
// Lastly, the server responds with the actual content.
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
MockRead("hello"),
};
// An incorrect reconnect would cause this to be read.
MockRead data_reads2[] = {
MockRead(SYNCHRONOUS, ERR_FAILED),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge));
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBar), callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(5, response->headers->GetContentLength());
}
// Test the request-challenge-retry sequence for basic auth, over a keep-alive
// connection and with a large response body to drain.
TEST_F(HttpNetworkTransactionTest, BasicAuthKeepAliveLargeBody) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
MockWrite data_writes1[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
// After calling trans.RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
// Respond with 5 kb of response body.
std::string large_body_string("Unauthorized");
large_body_string.append(5 * 1024, ' ');
large_body_string.append("\r\n");
MockRead data_reads1[] = {
MockRead("HTTP/1.1 401 Unauthorized\r\n"),
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
// 5134 = 12 + 5 * 1024 + 2
MockRead("Content-Length: 5134\r\n\r\n"),
MockRead(ASYNC, large_body_string.data(), large_body_string.size()),
// Lastly, the server responds with the actual content.
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
MockRead("hello"),
};
// An incorrect reconnect would cause this to be read.
MockRead data_reads2[] = {
MockRead(SYNCHRONOUS, ERR_FAILED),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge));
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBar), callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(5, response->headers->GetContentLength());
}
// Test the request-challenge-retry sequence for basic auth, over a keep-alive
// connection, but the server gets impatient and closes the connection.
TEST_F(HttpNetworkTransactionTest, BasicAuthKeepAliveImpatientServer) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
MockWrite data_writes1[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
// This simulates the seemingly successful write to a closed connection
// if the bug is not fixed.
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 401 Unauthorized\r\n"),
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 14\r\n\r\n"),
// Tell MockTCPClientSocket to simulate the server closing the connection.
MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
MockRead("Unauthorized\r\n"),
MockRead(SYNCHRONOUS, OK), // The server closes the connection.
};
// After calling trans.RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite data_writes2[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
// Lastly, the server responds with the actual content.
MockRead data_reads2[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
MockRead("hello"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge));
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBar), callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(5, response->headers->GetContentLength());
}
// Test the request-challenge-retry sequence for basic auth, over a connection
// that requires a restart when setting up an SSL tunnel.
TEST_F(HttpNetworkTransactionTest, BasicAuthProxyNoKeepAliveHttp10) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
// when the no authentication data flag is set.
request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a non-persistent
// connection.
MockRead data_reads1[] = {
// No credentials.
MockRead("HTTP/1.0 407 Proxy Authentication Required\r\n"),
MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n\r\n"),
};
// Since the first connection couldn't be reused, need to establish another
// once given credentials.
MockWrite data_writes2[] = {
// After calling trans->RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads2[] = {
MockRead("HTTP/1.0 200 Connection Established\r\n\r\n"),
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
MockRead(SYNCHRONOUS, "hello"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback1;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
TestNetLogEntry::List entries;
log.GetEntries(&entries);
size_t pos = ExpectLogContainsSomewhere(
entries, 0, NetLogEventType::HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
NetLogEventPhase::NONE);
ExpectLogContainsSomewhere(
entries, pos,
NetLogEventType::HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
NetLogEventPhase::NONE);
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->headers->IsKeepAlive());
ASSERT_TRUE(response->headers);
EXPECT_EQ(407, response->headers->response_code());
EXPECT_TRUE(HttpVersion(1, 0) == response->headers->GetHttpVersion());
EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge));
LoadTimingInfo load_timing_info;
// CONNECT requests and responses are handled at the connect job level, so
// the transaction does not yet have a connection.
EXPECT_FALSE(trans->GetLoadTimingInfo(&load_timing_info));
TestCompletionCallback callback2;
rv =
trans->RestartWithAuth(AuthCredentials(kFoo, kBar), callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans->GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(5, response->headers->GetContentLength());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
// The password prompt info should not be set.
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReusedWithPac(load_timing_info,
CONNECT_TIMING_HAS_SSL_TIMES);
trans.reset();
session->CloseAllConnections();
}
// Test the request-challenge-retry sequence for basic auth, over a connection
// that requires a restart when setting up an SSL tunnel.
TEST_F(HttpNetworkTransactionTest, BasicAuthProxyNoKeepAliveHttp11) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
// when the no authentication data flag is set.
request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a non-persistent
// connection.
MockRead data_reads1[] = {
// No credentials.
MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Proxy-Connection: close\r\n\r\n"),
};
MockWrite data_writes2[] = {
// After calling trans->RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads2[] = {
MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
MockRead(SYNCHRONOUS, "hello"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback1;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
TestNetLogEntry::List entries;
log.GetEntries(&entries);
size_t pos = ExpectLogContainsSomewhere(
entries, 0, NetLogEventType::HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
NetLogEventPhase::NONE);
ExpectLogContainsSomewhere(
entries, pos,
NetLogEventType::HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
NetLogEventPhase::NONE);
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->headers->IsKeepAlive());
ASSERT_TRUE(response->headers);
EXPECT_EQ(407, response->headers->response_code());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge));
LoadTimingInfo load_timing_info;
// CONNECT requests and responses are handled at the connect job level, so
// the transaction does not yet have a connection.
EXPECT_FALSE(trans->GetLoadTimingInfo(&load_timing_info));
TestCompletionCallback callback2;
rv = trans->RestartWithAuth(
AuthCredentials(kFoo, kBar), callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans->GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(5, response->headers->GetContentLength());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
// The password prompt info should not be set.
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReusedWithPac(load_timing_info,
CONNECT_TIMING_HAS_SSL_TIMES);
trans.reset();
session->CloseAllConnections();
}
// Test the request-challenge-retry sequence for basic auth, over a keep-alive
// proxy connection with HTTP/1.0 responses, when setting up an SSL tunnel.
TEST_F(HttpNetworkTransactionTest, BasicAuthProxyKeepAliveHttp10) {
// On the second pass, the body read of the auth challenge is synchronous, so
// IsConnectedAndIdle returns false. The socket should still be drained and
// reused. See http://crbug.com/544255.
for (int i = 0; i < 2; ++i) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
// Ensure that proxy authentication is attempted even
// when the no authentication data flag is set.
request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixed("myproxy:70",
TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite(ASYNC, 0,
"CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
// After calling trans.RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite(ASYNC, 3,
"CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: Basic Zm9vOmJheg==\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a persistent
// connection. (Since it's HTTP/1.0, keep-alive has to be explicit.)
MockRead data_reads1[] = {
// No credentials.
MockRead(ASYNC, 1,
"HTTP/1.0 407 Proxy Authentication Required\r\n"
"Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"
"Proxy-Connection: keep-alive\r\n"
"Content-Length: 10\r\n\r\n"),
MockRead(i == 0 ? ASYNC : SYNCHRONOUS, 2, "0123456789"),
// Wrong credentials (wrong password).
MockRead(ASYNC, 4,
"HTTP/1.0 407 Proxy Authentication Required\r\n"
"Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"
"Proxy-Connection: keep-alive\r\n"
"Content-Length: 10\r\n\r\n"),
// No response body because the test stops reading here.
MockRead(SYNCHRONOUS, ERR_UNEXPECTED, 5),
};
SequencedSocketData data1(data_reads1, data_writes1);
data1.set_busy_before_sync_reads(true);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(callback1.GetResult(rv), IsOk());
TestNetLogEntry::List entries;
log.GetEntries(&entries);
size_t pos = ExpectLogContainsSomewhere(
entries, 0, NetLogEventType::HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
NetLogEventPhase::NONE);
ExpectLogContainsSomewhere(
entries, pos,
NetLogEventType::HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
NetLogEventPhase::NONE);
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(407, response->headers->response_code());
EXPECT_EQ(10, response->headers->GetContentLength());
EXPECT_TRUE(HttpVersion(1, 0) == response->headers->GetHttpVersion());
EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge));
TestCompletionCallback callback2;
// Wrong password (should be "bar").
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBaz),
callback2.callback());
EXPECT_THAT(callback2.GetResult(rv), IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(407, response->headers->response_code());
EXPECT_EQ(10, response->headers->GetContentLength());
EXPECT_TRUE(HttpVersion(1, 0) == response->headers->GetHttpVersion());
EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge));
// Flush the idle socket before the NetLog and HttpNetworkTransaction go
// out of scope.
session->CloseAllConnections();
}
}
// Test the request-challenge-retry sequence for basic auth, over a keep-alive
// proxy connection with HTTP/1.1 responses, when setting up an SSL tunnel.
TEST_F(HttpNetworkTransactionTest, BasicAuthProxyKeepAliveHttp11) {
// On the second pass, the body read of the auth challenge is synchronous, so
// IsConnectedAndIdle returns false. The socket should still be drained and
// reused. See http://crbug.com/544255.
for (int i = 0; i < 2; ++i) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
// Ensure that proxy authentication is attempted even
// when the no authentication data flag is set.
request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixed("myproxy:70",
TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite(ASYNC, 0,
"CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
// After calling trans.RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite(ASYNC, 3,
"CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: Basic Zm9vOmJheg==\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a persistent
// connection. (Since it's HTTP/1.0, keep-alive has to be explicit.)
MockRead data_reads1[] = {
// No credentials.
MockRead(ASYNC, 1,
"HTTP/1.1 407 Proxy Authentication Required\r\n"
"Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"
"Content-Length: 10\r\n\r\n"),
MockRead(i == 0 ? ASYNC : SYNCHRONOUS, 2, "0123456789"),
// Wrong credentials (wrong password).
MockRead(ASYNC, 4,
"HTTP/1.1 407 Proxy Authentication Required\r\n"
"Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"
"Content-Length: 10\r\n\r\n"),
// No response body because the test stops reading here.
MockRead(SYNCHRONOUS, ERR_UNEXPECTED, 5),
};
SequencedSocketData data1(data_reads1, data_writes1);
data1.set_busy_before_sync_reads(true);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(callback1.GetResult(rv), IsOk());
TestNetLogEntry::List entries;
log.GetEntries(&entries);
size_t pos = ExpectLogContainsSomewhere(
entries, 0, NetLogEventType::HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
NetLogEventPhase::NONE);
ExpectLogContainsSomewhere(
entries, pos,
NetLogEventType::HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
NetLogEventPhase::NONE);
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(407, response->headers->response_code());
EXPECT_EQ(10, response->headers->GetContentLength());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge));
EXPECT_FALSE(response->did_use_http_auth);
TestCompletionCallback callback2;
// Wrong password (should be "bar").
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBaz),
callback2.callback());
EXPECT_THAT(callback2.GetResult(rv), IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(407, response->headers->response_code());
EXPECT_EQ(10, response->headers->GetContentLength());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge));
EXPECT_TRUE(response->did_use_http_auth);
// Flush the idle socket before the NetLog and HttpNetworkTransaction go
// out of scope.
session->CloseAllConnections();
}
}
// Test the request-challenge-retry sequence for basic auth, over a keep-alive
// proxy connection with HTTP/1.1 responses, when setting up an SSL tunnel, in
// the case the server sends extra data on the original socket, so it can't be
// reused.
TEST_F(HttpNetworkTransactionTest, BasicAuthProxyKeepAliveExtraData) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
// when the no authentication data flag is set.
request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite(ASYNC, 0,
"CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a persistent, but sends
// extra data, so the socket cannot be reused.
MockRead data_reads1[] = {
// No credentials.
MockRead(ASYNC, 1,
"HTTP/1.1 407 Proxy Authentication Required\r\n"
"Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"
"Content-Length: 10\r\n\r\n"),
MockRead(SYNCHRONOUS, 2, "0123456789"),
MockRead(SYNCHRONOUS, 3, "I'm broken!"),
};
MockWrite data_writes2[] = {
// After calling trans->RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite(ASYNC, 0,
"CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
MockWrite(ASYNC, 2,
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads2[] = {
MockRead(ASYNC, 1, "HTTP/1.1 200 Connection Established\r\n\r\n"),
MockRead(ASYNC, 3,
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=iso-8859-1\r\n"
"Content-Length: 5\r\n\r\n"),
// No response body because the test stops reading here.
MockRead(SYNCHRONOUS, ERR_UNEXPECTED, 4),
};
SequencedSocketData data1(data_reads1, data_writes1);
data1.set_busy_before_sync_reads(true);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
SequencedSocketData data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback1;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(callback1.GetResult(rv), IsOk());
TestNetLogEntry::List entries;
log.GetEntries(&entries);
size_t pos = ExpectLogContainsSomewhere(
entries, 0, NetLogEventType::HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
NetLogEventPhase::NONE);
ExpectLogContainsSomewhere(
entries, pos,
NetLogEventType::HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
NetLogEventPhase::NONE);
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(407, response->headers->response_code());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge));
LoadTimingInfo load_timing_info;
// CONNECT requests and responses are handled at the connect job level, so
// the transaction does not yet have a connection.
EXPECT_FALSE(trans->GetLoadTimingInfo(&load_timing_info));
TestCompletionCallback callback2;
rv =
trans->RestartWithAuth(AuthCredentials(kFoo, kBar), callback2.callback());
EXPECT_THAT(callback2.GetResult(rv), IsOk());
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(5, response->headers->GetContentLength());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
// The password prompt info should not be set.
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReusedWithPac(load_timing_info,
CONNECT_TIMING_HAS_SSL_TIMES);
trans.reset();
session->CloseAllConnections();
}
// Test the case a proxy closes a socket while the challenge body is being
// drained.
TEST_F(HttpNetworkTransactionTest, BasicAuthProxyKeepAliveHangupDuringBody) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
// Ensure that proxy authentication is attempted even
// when the no authentication data flag is set.
request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session = CreateSession(&session_deps_);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a persistent
// connection.
MockRead data_reads1[] = {
// No credentials.
MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Length: 10\r\n\r\n"), MockRead("spam!"),
// Server hands up in the middle of the body.
MockRead(ASYNC, ERR_CONNECTION_CLOSED),
};
MockWrite data_writes2[] = {
// After calling trans.RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads2[] = {
MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
MockRead(SYNCHRONOUS, "hello"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(407, response->headers->response_code());
EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge));
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBar), callback.callback());
EXPECT_THAT(callback.GetResult(rv), IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(200, response->headers->response_code());
std::string body;
EXPECT_THAT(ReadTransaction(&trans, &body), IsOk());
EXPECT_EQ("hello", body);
}
// Test that we don't read the response body when we fail to establish a tunnel,
// even if the user cancels the proxy's auth attempt.
TEST_F(HttpNetworkTransactionTest, BasicAuthProxyCancelTunnel) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
// The proxy responds to the connect with a 407.
MockRead data_reads[] = {
MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Length: 10\r\n\r\n"),
MockRead("0123456789"),
MockRead(SYNCHRONOUS, ERR_UNEXPECTED),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(407, response->headers->response_code());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsError(ERR_TUNNEL_CONNECTION_FAILED));
// Flush the idle socket before the HttpNetworkTransaction goes out of scope.
session->CloseAllConnections();
}
// Test that we don't pass extraneous headers from the proxy's response to the
// caller when the proxy responds to CONNECT with 407.
TEST_F(HttpNetworkTransactionTest, SanitizeProxyAuthHeaders) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
// The proxy responds to the connect with a 407.
MockRead data_reads[] = {
MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
MockRead("X-Foo: bar\r\n"),
MockRead("Set-Cookie: foo=bar\r\n"),
MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Length: 10\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_UNEXPECTED),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(407, response->headers->response_code());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
EXPECT_FALSE(response->headers->HasHeader("X-Foo"));
EXPECT_FALSE(response->headers->HasHeader("Set-Cookie"));
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsError(ERR_TUNNEL_CONNECTION_FAILED));
// Flush the idle socket before the HttpNetworkTransaction goes out of scope.
session->CloseAllConnections();
}
// Test when a server (non-proxy) returns a 407 (proxy-authenticate).
// The request should fail with ERR_UNEXPECTED_PROXY_AUTH.
TEST_F(HttpNetworkTransactionTest, UnexpectedProxyAuth) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// We are using a DIRECT connection (i.e. no proxy) for this session.
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes1[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.0 407 Proxy Auth required\r\n"),
MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
// Large content-length -- won't matter, as connection will be reset.
MockRead("Content-Length: 10000\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_UNEXPECTED_PROXY_AUTH));
}
// Tests when an HTTPS server (non-proxy) returns a 407 (proxy-authentication)
// through a non-authenticating proxy. The request should fail with
// ERR_UNEXPECTED_PROXY_AUTH.
// Note that it is impossible to detect if an HTTP server returns a 407 through
// a non-authenticating proxy - there is nothing to indicate whether the
// response came from the proxy or the server, so it is treated as if the proxy
// issued the challenge.
TEST_F(HttpNetworkTransactionTest, HttpsServerRequestsProxyAuthThroughProxy) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
MockRead("HTTP/1.1 407 Unauthorized\r\n"),
MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_UNEXPECTED_PROXY_AUTH));
TestNetLogEntry::List entries;
log.GetEntries(&entries);
size_t pos = ExpectLogContainsSomewhere(
entries, 0, NetLogEventType::HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
NetLogEventPhase::NONE);
ExpectLogContainsSomewhere(
entries, pos,
NetLogEventType::HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
NetLogEventPhase::NONE);
}
// Test a proxy auth scheme that allows default credentials and a proxy server
// that uses non-persistent connections.
TEST_F(HttpNetworkTransactionTest,
AuthAllowsDefaultCredentialsTunnelConnectionClose) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
auto auth_handler_factory = std::make_unique<HttpAuthHandlerMock::Factory>();
auth_handler_factory->set_do_init_from_challenge(true);
auto mock_handler = std::make_unique<HttpAuthHandlerMock>();
mock_handler->set_allows_default_credentials(true);
auth_handler_factory->AddMockHandler(mock_handler.release(),
HttpAuth::AUTH_PROXY);
session_deps_.http_auth_handler_factory = std::move(auth_handler_factory);
// Add NetLog just so can verify load timing information gets a NetLog ID.
NetLog net_log;
session_deps_.net_log = &net_log;
std::unique_ptr<HttpNetworkSession> session = CreateSession(&session_deps_);
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a non-persistent
// connection.
MockRead data_reads1[] = {
// No credentials.
MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
MockRead("Proxy-Authenticate: Mock\r\n"),
MockRead("Proxy-Connection: close\r\n\r\n"),
};
// Since the first connection couldn't be reused, need to establish another
// once given credentials.
MockWrite data_writes2[] = {
// After calling trans->RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: auth_token\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads2[] = {
MockRead("HTTP/1.0 200 Connection Established\r\n\r\n"),
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
MockRead(SYNCHRONOUS, "hello"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_FALSE(response->headers->IsKeepAlive());
EXPECT_EQ(407, response->headers->response_code());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
EXPECT_TRUE(trans->IsReadyToRestartForAuth());
EXPECT_FALSE(response->auth_challenge.has_value());
LoadTimingInfo load_timing_info;
// CONNECT requests and responses are handled at the connect job level, so
// the transaction does not yet have a connection.
EXPECT_FALSE(trans->GetLoadTimingInfo(&load_timing_info));
rv = trans->RestartWithAuth(AuthCredentials(), callback.callback());
EXPECT_THAT(callback.GetResult(rv), IsOk());
response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(5, response->headers->GetContentLength());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
// The password prompt info should not be set.
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReusedWithPac(load_timing_info,
CONNECT_TIMING_HAS_SSL_TIMES);
trans.reset();
session->CloseAllConnections();
}
// Test a proxy auth scheme that allows default credentials and a proxy server
// that hangs up when credentials are initially sent.
TEST_F(HttpNetworkTransactionTest,
AuthAllowsDefaultCredentialsTunnelServerClosesConnection) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
auto auth_handler_factory = std::make_unique<HttpAuthHandlerMock::Factory>();
auth_handler_factory->set_do_init_from_challenge(true);
auto mock_handler = std::make_unique<HttpAuthHandlerMock>();
mock_handler->set_allows_default_credentials(true);
auth_handler_factory->AddMockHandler(mock_handler.release(),
HttpAuth::AUTH_PROXY);
session_deps_.http_auth_handler_factory = std::move(auth_handler_factory);
// Add NetLog just so can verify load timing information gets a NetLog ID.
NetLog net_log;
session_deps_.net_log = &net_log;
std::unique_ptr<HttpNetworkSession> session = CreateSession(&session_deps_);
// Should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: auth_token\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a non-persistent
// connection.
MockRead data_reads1[] = {
// No credentials.
MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
MockRead("Proxy-Authenticate: Mock\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_CONNECTION_CLOSED),
};
// Since the first connection was closed, need to establish another once given
// credentials.
MockWrite data_writes2[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: auth_token\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads2[] = {
MockRead("HTTP/1.0 200 Connection Established\r\n\r\n"),
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
MockRead(SYNCHRONOUS, "hello"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(407, response->headers->response_code());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
EXPECT_TRUE(trans->IsReadyToRestartForAuth());
EXPECT_FALSE(response->auth_challenge.has_value());
LoadTimingInfo load_timing_info;
// CONNECT requests and responses are handled at the connect job level, so
// the transaction does not yet have a connection.
EXPECT_FALSE(trans->GetLoadTimingInfo(&load_timing_info));
rv = trans->RestartWithAuth(AuthCredentials(), callback.callback());
EXPECT_THAT(callback.GetResult(rv), IsOk());
response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(5, response->headers->GetContentLength());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
// The password prompt info should not be set.
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReusedWithPac(load_timing_info,
CONNECT_TIMING_HAS_SSL_TIMES);
trans.reset();
session->CloseAllConnections();
}
// Test a proxy auth scheme that allows default credentials and a proxy server
// that hangs up when credentials are initially sent, and hangs up again when
// they are retried.
TEST_F(HttpNetworkTransactionTest,
AuthAllowsDefaultCredentialsTunnelServerClosesConnectionTwice) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
auto auth_handler_factory = std::make_unique<HttpAuthHandlerMock::Factory>();
auth_handler_factory->set_do_init_from_challenge(true);
auto mock_handler = std::make_unique<HttpAuthHandlerMock>();
mock_handler->set_allows_default_credentials(true);
auth_handler_factory->AddMockHandler(mock_handler.release(),
HttpAuth::AUTH_PROXY);
session_deps_.http_auth_handler_factory = std::move(auth_handler_factory);
// Add NetLog just so can verify load timing information gets a NetLog ID.
NetLog net_log;
session_deps_.net_log = &net_log;
std::unique_ptr<HttpNetworkSession> session = CreateSession(&session_deps_);
// Should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: auth_token\r\n\r\n"),
};
// The proxy responds to the connect with a 407, and then hangs up after the
// second request is sent.
MockRead data_reads1[] = {
// No credentials.
MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
MockRead("Content-Length: 0\r\n"),
MockRead("Proxy-Connection: keep-alive\r\n"),
MockRead("Proxy-Authenticate: Mock\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_CONNECTION_CLOSED),
};
// HttpNetworkTransaction sees a reused connection that was closed with
// ERR_CONNECTION_CLOSED, realized it might have been a race, so retries the
// request.
MockWrite data_writes2[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
// The proxy, having had more than enough of us, just hangs up.
MockRead data_reads2[] = {
// No credentials.
MockRead(SYNCHRONOUS, ERR_CONNECTION_CLOSED),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(407, response->headers->response_code());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
EXPECT_TRUE(trans->IsReadyToRestartForAuth());
EXPECT_FALSE(response->auth_challenge.has_value());
LoadTimingInfo load_timing_info;
EXPECT_FALSE(trans->GetLoadTimingInfo(&load_timing_info));
rv = trans->RestartWithAuth(AuthCredentials(), callback.callback());
EXPECT_THAT(callback.GetResult(rv), IsError(ERR_EMPTY_RESPONSE));
trans.reset();
session->CloseAllConnections();
}
// This test exercises an odd edge case where the proxy closes the connection
// after the authentication handshake is complete. Presumably this technique is
// used in lieu of returning a 403 or 5xx status code when the authentication
// succeeds, but the user is not authorized to connect to the destination
// server. There's no standard for what a proxy should do to indicate a blocked
// site.
TEST_F(HttpNetworkTransactionTest,
AuthAllowsDefaultCredentialsTunnelConnectionClosesBeforeBody) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
auto auth_handler_factory = std::make_unique<HttpAuthHandlerMock::Factory>();
auth_handler_factory->set_do_init_from_challenge(true);
// Create two mock AuthHandlers. This is because the transaction gets retried
// after the first ERR_CONNECTION_CLOSED since it's ambiguous whether there
// was a real network error.
//
// The handlers support both default and explicit credentials. The retry
// mentioned above should be able to reuse the default identity. Thus there
// should never be a need to prompt for explicit credentials.
auto mock_handler = std::make_unique<HttpAuthHandlerMock>();
mock_handler->set_allows_default_credentials(true);
mock_handler->set_allows_explicit_credentials(true);
mock_handler->set_connection_based(true);
auth_handler_factory->AddMockHandler(mock_handler.release(),
HttpAuth::AUTH_PROXY);
mock_handler = std::make_unique<HttpAuthHandlerMock>();
mock_handler->set_allows_default_credentials(true);
mock_handler->set_allows_explicit_credentials(true);
mock_handler->set_connection_based(true);
auth_handler_factory->AddMockHandler(mock_handler.release(),
HttpAuth::AUTH_PROXY);
session_deps_.http_auth_handler_factory = std::move(auth_handler_factory);
NetLog net_log;
session_deps_.net_log = &net_log;
std::unique_ptr<HttpNetworkSession> session = CreateSession(&session_deps_);
// Data for both sockets.
//
// Writes are for the tunnel establishment attempts and the
// authentication handshake.
MockWrite data_writes1[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: auth_token\r\n\r\n"),
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: auth_token\r\n\r\n"),
};
// The server side of the authentication handshake. Note that the response to
// the final CONNECT request is ERR_CONNECTION_CLOSED.
MockRead data_reads1[] = {
MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
MockRead("Content-Length: 0\r\n"),
MockRead("Proxy-Connection: keep-alive\r\n"),
MockRead("Proxy-Authenticate: Mock\r\n\r\n"),
MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
MockRead("Content-Length: 0\r\n"),
MockRead("Proxy-Connection: keep-alive\r\n"),
MockRead("Proxy-Authenticate: Mock foo\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_CONNECTION_CLOSED),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
// The second socket is for the reconnection attempt. Data is identical to the
// first attempt.
StaticSocketDataProvider data2(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
// Two rounds per handshake. After one retry, the error is propagated up the
// stack.
for (int i = 0; i < 4; ++i) {
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(407, response->headers->response_code());
ASSERT_TRUE(trans->IsReadyToRestartForAuth());
rv = trans->RestartWithAuth(AuthCredentials(), callback.callback());
}
// One shall be the number thou shalt retry, and the number of the retrying
// shall be one. Two shalt thou not retry, neither retry thou zero, excepting
// that thou then proceed to one. Three is right out. Once the number one,
// being the first number, be reached, then lobbest thou thy
// ERR_CONNECTION_CLOSED towards they network transaction, who shall snuff it.
EXPECT_EQ(ERR_CONNECTION_CLOSED, callback.GetResult(rv));
trans.reset();
session->CloseAllConnections();
}
// Test a proxy auth scheme that allows default credentials and a proxy server
// that hangs up when credentials are initially sent, and sends a challenge
// again they are retried.
TEST_F(HttpNetworkTransactionTest,
AuthAllowsDefaultCredentialsTunnelServerChallengesTwice) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
auto auth_handler_factory = std::make_unique<HttpAuthHandlerMock::Factory>();
auth_handler_factory->set_do_init_from_challenge(true);
auto mock_handler = std::make_unique<HttpAuthHandlerMock>();
mock_handler->set_allows_default_credentials(true);
auth_handler_factory->AddMockHandler(mock_handler.release(),
HttpAuth::AUTH_PROXY);
// Add another handler for the second challenge. It supports default
// credentials, but they shouldn't be used, since they were already tried.
mock_handler = std::make_unique<HttpAuthHandlerMock>();
mock_handler->set_allows_default_credentials(true);
auth_handler_factory->AddMockHandler(mock_handler.release(),
HttpAuth::AUTH_PROXY);
session_deps_.http_auth_handler_factory = std::move(auth_handler_factory);
// Add NetLog just so can verify load timing information gets a NetLog ID.
NetLog net_log;
session_deps_.net_log = &net_log;
std::unique_ptr<HttpNetworkSession> session = CreateSession(&session_deps_);
// Should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a non-persistent
// connection.
MockRead data_reads1[] = {
// No credentials.
MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
MockRead("Proxy-Authenticate: Mock\r\n"),
MockRead("Proxy-Connection: close\r\n\r\n"),
};
// Since the first connection was closed, need to establish another once given
// credentials.
MockWrite data_writes2[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: auth_token\r\n\r\n"),
};
MockRead data_reads2[] = {
MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
MockRead("Proxy-Authenticate: Mock\r\n"),
MockRead("Proxy-Connection: close\r\n\r\n"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(407, response->headers->response_code());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
EXPECT_TRUE(trans->IsReadyToRestartForAuth());
EXPECT_FALSE(response->auth_challenge.has_value());
LoadTimingInfo load_timing_info;
EXPECT_FALSE(trans->GetLoadTimingInfo(&load_timing_info));
rv = trans->RestartWithAuth(AuthCredentials(), callback.callback());
EXPECT_THAT(callback.GetResult(rv), IsOk());
response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(407, response->headers->response_code());
EXPECT_FALSE(trans->IsReadyToRestartForAuth());
EXPECT_TRUE(response->auth_challenge.has_value());
trans.reset();
session->CloseAllConnections();
}
// A more nuanced test than GenerateAuthToken test which asserts that
// ERR_INVALID_AUTH_CREDENTIALS does not cause the auth scheme to be
// unnecessarily invalidated, and that if the server co-operates, the
// authentication handshake can continue with the same scheme but with a
// different identity.
TEST_F(HttpNetworkTransactionTest, NonPermanentGenerateAuthTokenError) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
auto auth_handler_factory = std::make_unique<HttpAuthHandlerMock::Factory>();
auth_handler_factory->set_do_init_from_challenge(true);
// First handler. Uses default credentials, but barfs at generate auth token.
auto mock_handler = std::make_unique<HttpAuthHandlerMock>();
mock_handler->set_allows_default_credentials(true);
mock_handler->set_allows_explicit_credentials(true);
mock_handler->set_connection_based(true);
mock_handler->SetGenerateExpectation(true, ERR_INVALID_AUTH_CREDENTIALS);
auth_handler_factory->AddMockHandler(mock_handler.release(),
HttpAuth::AUTH_SERVER);
// Add another handler for the second challenge. It supports default
// credentials, but they shouldn't be used, since they were already tried.
mock_handler = std::make_unique<HttpAuthHandlerMock>();
mock_handler->set_allows_default_credentials(true);
mock_handler->set_allows_explicit_credentials(true);
mock_handler->set_connection_based(true);
auth_handler_factory->AddMockHandler(mock_handler.release(),
HttpAuth::AUTH_SERVER);
session_deps_.http_auth_handler_factory = std::move(auth_handler_factory);
std::unique_ptr<HttpNetworkSession> session = CreateSession(&session_deps_);
MockWrite data_writes1[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 401 Authentication Required\r\n"
"WWW-Authenticate: Mock\r\n"
"Connection: keep-alive\r\n\r\n"),
};
// Identical to data_writes1[]. The AuthHandler encounters a
// ERR_INVALID_AUTH_CREDENTIALS during the GenerateAuthToken stage, so the
// transaction procceds without an authorization header.
MockWrite data_writes2[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads2[] = {
MockRead("HTTP/1.1 401 Authentication Required\r\n"
"WWW-Authenticate: Mock\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockWrite data_writes3[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: auth_token\r\n\r\n"),
};
MockRead data_reads3[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 5\r\n"
"Content-Type: text/plain\r\n"
"Connection: keep-alive\r\n\r\n"
"Hello"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
StaticSocketDataProvider data3(data_reads3, data_writes3);
session_deps_.socket_factory->AddSocketDataProvider(&data3);
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
// The following three tests assert that an authentication challenge was
// received and that the stack is ready to respond to the challenge using
// ambient credentials.
EXPECT_EQ(401, response->headers->response_code());
EXPECT_TRUE(trans->IsReadyToRestartForAuth());
EXPECT_FALSE(response->auth_challenge.has_value());
rv = trans->RestartWithAuth(AuthCredentials(), callback.callback());
EXPECT_THAT(callback.GetResult(rv), IsOk());
response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
// The following three tests assert that an authentication challenge was
// received and that the stack needs explicit credentials before it is ready
// to respond to the challenge.
EXPECT_EQ(401, response->headers->response_code());
EXPECT_FALSE(trans->IsReadyToRestartForAuth());
EXPECT_TRUE(response->auth_challenge.has_value());
rv = trans->RestartWithAuth(AuthCredentials(), callback.callback());
EXPECT_THAT(callback.GetResult(rv), IsOk());
response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(200, response->headers->response_code());
trans.reset();
session->CloseAllConnections();
}
// Proxy resolver that returns a proxy with the same host and port for different
// schemes, based on the path of the URL being requests.
class SameProxyWithDifferentSchemesProxyResolver : public ProxyResolver {
public:
SameProxyWithDifferentSchemesProxyResolver() {}
~SameProxyWithDifferentSchemesProxyResolver() override {}
static std::string ProxyHostPortPairAsString() { return "proxy.test:10000"; }
static HostPortPair ProxyHostPortPair() {
return HostPortPair::FromString(ProxyHostPortPairAsString());
}
// ProxyResolver implementation.
int GetProxyForURL(const GURL& url,
ProxyInfo* results,
CompletionOnceCallback callback,
std::unique_ptr<Request>* request,
const NetLogWithSource& /*net_log*/) override {
*results = ProxyInfo();
results->set_traffic_annotation(
MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS));
if (url.path() == "/socks4") {
results->UsePacString("SOCKS " + ProxyHostPortPairAsString());
return OK;
}
if (url.path() == "/socks5") {
results->UsePacString("SOCKS5 " + ProxyHostPortPairAsString());
return OK;
}
if (url.path() == "/http") {
results->UsePacString("PROXY " + ProxyHostPortPairAsString());
return OK;
}
if (url.path() == "/https") {
results->UsePacString("HTTPS " + ProxyHostPortPairAsString());
return OK;
}
if (url.path() == "/https_trusted") {
results->UseProxyServer(ProxyServer(ProxyServer::SCHEME_HTTPS,
ProxyHostPortPair(),
true /* is_trusted_proxy */));
return OK;
}
NOTREACHED();
return ERR_NOT_IMPLEMENTED;
}
private:
DISALLOW_COPY_AND_ASSIGN(SameProxyWithDifferentSchemesProxyResolver);
};
class SameProxyWithDifferentSchemesProxyResolverFactory
: public ProxyResolverFactory {
public:
SameProxyWithDifferentSchemesProxyResolverFactory()
: ProxyResolverFactory(false) {}
int CreateProxyResolver(const scoped_refptr<PacFileData>& pac_script,
std::unique_ptr<ProxyResolver>* resolver,
CompletionOnceCallback callback,
std::unique_ptr<Request>* request) override {
*resolver = std::make_unique<SameProxyWithDifferentSchemesProxyResolver>();
return OK;
}
private:
DISALLOW_COPY_AND_ASSIGN(SameProxyWithDifferentSchemesProxyResolverFactory);
};
// Check that when different proxy schemes are all applied to a proxy at the
// same address, the connections are not grouped together. i.e., a request to
// foo.com using proxy.com as an HTTPS proxy won't use the same socket as a
// request to foo.com using proxy.com as an HTTP proxy.
TEST_F(HttpNetworkTransactionTest, SameDestinationForDifferentProxyTypes) {
session_deps_.proxy_resolution_service =
std::make_unique<ProxyResolutionService>(
std::make_unique<ProxyConfigServiceFixed>(ProxyConfigWithAnnotation(
ProxyConfig::CreateAutoDetect(), TRAFFIC_ANNOTATION_FOR_TESTS)),
std::make_unique<SameProxyWithDifferentSchemesProxyResolverFactory>(),
nullptr);
std::unique_ptr<HttpNetworkSession> session = CreateSession(&session_deps_);
MockWrite socks_writes[] = {
MockWrite(SYNCHRONOUS, kSOCKS4OkRequestLocalHostPort80,
kSOCKS4OkRequestLocalHostPort80Length),
MockWrite(SYNCHRONOUS,
"GET /socks4 HTTP/1.1\r\n"
"Host: test\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead socks_reads[] = {
MockRead(SYNCHRONOUS, kSOCKS4OkReply, kSOCKS4OkReplyLength),
MockRead("HTTP/1.0 200 OK\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 15\r\n\r\n"
"SOCKS4 Response"),
};
StaticSocketDataProvider socks_data(socks_reads, socks_writes);
session_deps_.socket_factory->AddSocketDataProvider(&socks_data);
const char kSOCKS5Request[] = {
0x05, // Version
0x01, // Command (CONNECT)
0x00, // Reserved
0x03, // Address type (DOMAINNAME)
0x04, // Length of domain (4)
't', 'e', 's', 't', // Domain string
0x00, 0x50, // 16-bit port (80)
};
MockWrite socks5_writes[] = {
MockWrite(ASYNC, kSOCKS5GreetRequest, kSOCKS5GreetRequestLength),
MockWrite(ASYNC, kSOCKS5Request, base::size(kSOCKS5Request)),
MockWrite(SYNCHRONOUS,
"GET /socks5 HTTP/1.1\r\n"
"Host: test\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead socks5_reads[] = {
MockRead(ASYNC, kSOCKS5GreetResponse, kSOCKS5GreetResponseLength),
MockRead(ASYNC, kSOCKS5OkResponse, kSOCKS5OkResponseLength),
MockRead("HTTP/1.0 200 OK\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 15\r\n\r\n"
"SOCKS5 Response"),
};
StaticSocketDataProvider socks5_data(socks5_reads, socks5_writes);
session_deps_.socket_factory->AddSocketDataProvider(&socks5_data);
MockWrite http_writes[] = {
MockWrite(SYNCHRONOUS,
"GET http://test/http HTTP/1.1\r\n"
"Host: test\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
MockRead http_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Proxy-Connection: keep-alive\r\n"
"Content-Length: 13\r\n\r\n"
"HTTP Response"),
};
StaticSocketDataProvider http_data(http_reads, http_writes);
session_deps_.socket_factory->AddSocketDataProvider(&http_data);
MockWrite https_writes[] = {
MockWrite(SYNCHRONOUS,
"GET http://test/https HTTP/1.1\r\n"
"Host: test\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
MockRead https_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Proxy-Connection: keep-alive\r\n"
"Content-Length: 14\r\n\r\n"
"HTTPS Response"),
};
StaticSocketDataProvider https_data(https_reads, https_writes);
session_deps_.socket_factory->AddSocketDataProvider(&https_data);
SSLSocketDataProvider ssl(SYNCHRONOUS, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
MockWrite https_trusted_writes[] = {
MockWrite(SYNCHRONOUS,
"GET http://test/https_trusted HTTP/1.1\r\n"
"Host: test\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
MockRead https_trusted_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Proxy-Connection: keep-alive\r\n"
"Content-Length: 22\r\n\r\n"
"HTTPS Trusted Response"),
};
StaticSocketDataProvider trusted_https_data(https_trusted_reads,
https_trusted_writes);
session_deps_.socket_factory->AddSocketDataProvider(&trusted_https_data);
SSLSocketDataProvider ssl2(SYNCHRONOUS, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
struct TestCase {
GURL url;
std::string expected_response;
// How many idle sockets there should be in the SOCKS 4/5 proxy socket pools
// after the test.
int expected_idle_socks4_sockets;
int expected_idle_socks5_sockets;
// How many idle sockets there should be in the HTTP/HTTPS proxy socket
// pools after the test.
int expected_idle_http_sockets;
int expected_idle_https_sockets;
// How many idle sockets there should be in the HTTPS proxy socket pool with
// the ProxyServer's |is_trusted_proxy| bit set after the test.
int expected_idle_trusted_https_sockets;
} const kTestCases[] = {
{GURL("http://test/socks4"), "SOCKS4 Response", 1, 0, 0, 0, 0},
{GURL("http://test/socks5"), "SOCKS5 Response", 1, 1, 0, 0, 0},
{GURL("http://test/http"), "HTTP Response", 1, 1, 1, 0, 0},
{GURL("http://test/https"), "HTTPS Response", 1, 1, 1, 1, 0},
{GURL("http://test/https_trusted"), "HTTPS Trusted Response", 1, 1, 1, 1,
1},
};
for (const auto& test_case : kTestCases) {
HttpRequestInfo request;
request.method = "GET";
request.url = test_case.url;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkTransaction> trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY,
session.get());
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(200, response->headers->response_code());
std::string response_data;
EXPECT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ(test_case.expected_response, response_data);
// Return the socket to the socket pool, so can make sure it's not used for
// the next requests.
trans.reset();
base::RunLoop().RunUntilIdle();
// Check the number of idle sockets in the pool, to make sure that used
// sockets are indeed being returned to the socket pool. If each request
// doesn't return an idle socket to the pool, the test would incorrectly
// pass.
EXPECT_EQ(test_case.expected_idle_socks4_sockets,
session
->GetSocketPool(
HttpNetworkSession::NORMAL_SOCKET_POOL,
ProxyServer(ProxyServer::SCHEME_SOCKS4,
SameProxyWithDifferentSchemesProxyResolver::
ProxyHostPortPair()))
->IdleSocketCount());
EXPECT_EQ(test_case.expected_idle_socks5_sockets,
session
->GetSocketPool(
HttpNetworkSession::NORMAL_SOCKET_POOL,
ProxyServer(ProxyServer::SCHEME_SOCKS5,
SameProxyWithDifferentSchemesProxyResolver::
ProxyHostPortPair()))
->IdleSocketCount());
EXPECT_EQ(test_case.expected_idle_http_sockets,
session
->GetSocketPool(
HttpNetworkSession::NORMAL_SOCKET_POOL,
ProxyServer(ProxyServer::SCHEME_HTTP,
SameProxyWithDifferentSchemesProxyResolver::
ProxyHostPortPair()))
->IdleSocketCount());
EXPECT_EQ(test_case.expected_idle_https_sockets,
session
->GetSocketPool(
HttpNetworkSession::NORMAL_SOCKET_POOL,
ProxyServer(ProxyServer::SCHEME_HTTPS,
SameProxyWithDifferentSchemesProxyResolver::
ProxyHostPortPair()))
->IdleSocketCount());
EXPECT_EQ(test_case.expected_idle_trusted_https_sockets,
session
->GetSocketPool(
HttpNetworkSession::NORMAL_SOCKET_POOL,
ProxyServer(ProxyServer::SCHEME_HTTPS,
SameProxyWithDifferentSchemesProxyResolver::
ProxyHostPortPair(),
true /* is_trusted_proxy */))
->IdleSocketCount());
}
}
// Test the load timing for HTTPS requests with an HTTP proxy.
TEST_F(HttpNetworkTransactionTest, HttpProxyLoadTimingNoPacTwoRequests) {
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("https://www.example.org/1");
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("https://www.example.org/2");
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
MockWrite("GET /1 HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
MockWrite("GET /2 HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a persistent
// connection.
MockRead data_reads1[] = {
MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 1\r\n\r\n"),
MockRead(SYNCHRONOUS, "1"),
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 2\r\n\r\n"),
MockRead(SYNCHRONOUS, "22"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback1;
auto trans1 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans1->Start(&request1, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response1 = trans1->GetResponseInfo();
ASSERT_TRUE(response1);
EXPECT_TRUE(response1->proxy_server.is_http());
ASSERT_TRUE(response1->headers);
EXPECT_EQ(1, response1->headers->GetContentLength());
LoadTimingInfo load_timing_info1;
EXPECT_TRUE(trans1->GetLoadTimingInfo(&load_timing_info1));
TestLoadTimingNotReused(load_timing_info1, CONNECT_TIMING_HAS_SSL_TIMES);
trans1.reset();
TestCompletionCallback callback2;
auto trans2 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
rv = trans2->Start(&request2, callback2.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response2 = trans2->GetResponseInfo();
ASSERT_TRUE(response2);
EXPECT_TRUE(response2->proxy_server.is_http());
ASSERT_TRUE(response2->headers);
EXPECT_EQ(2, response2->headers->GetContentLength());
LoadTimingInfo load_timing_info2;
EXPECT_TRUE(trans2->GetLoadTimingInfo(&load_timing_info2));
TestLoadTimingReused(load_timing_info2);
EXPECT_EQ(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
trans2.reset();
session->CloseAllConnections();
}
// Test the load timing for HTTPS requests with an HTTP proxy and a PAC script.
TEST_F(HttpNetworkTransactionTest, HttpProxyLoadTimingWithPacTwoRequests) {
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("https://www.example.org/1");
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("https://www.example.org/2");
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
MockWrite("GET /1 HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
MockWrite("GET /2 HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a persistent
// connection.
MockRead data_reads1[] = {
MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 1\r\n\r\n"),
MockRead(SYNCHRONOUS, "1"),
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 2\r\n\r\n"),
MockRead(SYNCHRONOUS, "22"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback1;
auto trans1 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans1->Start(&request1, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response1 = trans1->GetResponseInfo();
ASSERT_TRUE(response1);
ASSERT_TRUE(response1->headers);
EXPECT_EQ(1, response1->headers->GetContentLength());
LoadTimingInfo load_timing_info1;
EXPECT_TRUE(trans1->GetLoadTimingInfo(&load_timing_info1));
TestLoadTimingNotReusedWithPac(load_timing_info1,
CONNECT_TIMING_HAS_SSL_TIMES);
trans1.reset();
TestCompletionCallback callback2;
auto trans2 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
rv = trans2->Start(&request2, callback2.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response2 = trans2->GetResponseInfo();
ASSERT_TRUE(response2);
ASSERT_TRUE(response2->headers);
EXPECT_EQ(2, response2->headers->GetContentLength());
LoadTimingInfo load_timing_info2;
EXPECT_TRUE(trans2->GetLoadTimingInfo(&load_timing_info2));
TestLoadTimingReusedWithPac(load_timing_info2);
EXPECT_EQ(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
trans2.reset();
session->CloseAllConnections();
}
// Test a simple get through an HTTPS Proxy.
TEST_F(HttpNetworkTransactionTest, HttpsProxyGet) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against https proxy server "proxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Since we have proxy, should use full url
MockWrite data_writes1[] = {
MockWrite(
"GET http://www.example.org/ HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReused(load_timing_info,
CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->proxy_server.is_https());
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(100, response->headers->GetContentLength());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
// The password prompt info should not be set.
EXPECT_FALSE(response->auth_challenge.has_value());
}
// Test a SPDY get through an HTTPS Proxy.
TEST_F(HttpNetworkTransactionTest, HttpsProxySpdyGet) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against https proxy server "proxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// fetch http://www.example.org/ via SPDY
spdy::SpdySerializedFrame req(
spdy_util_.ConstructSpdyGet("http://www.example.org/", 1, LOWEST));
MockWrite spdy_writes[] = {CreateMockWrite(req, 0)};
spdy::SpdySerializedFrame resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame data(spdy_util_.ConstructSpdyDataFrame(1, true));
MockRead spdy_reads[] = {
CreateMockRead(resp, 1), CreateMockRead(data, 2), MockRead(ASYNC, 0, 3),
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReused(load_timing_info,
CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->proxy_server.is_https());
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ(kUploadData, response_data);
}
// Verifies that a session which races and wins against the owning transaction
// (completing prior to host resolution), doesn't fail the transaction.
// Regression test for crbug.com/334413.
TEST_F(HttpNetworkTransactionTest, HttpsProxySpdyGetWithSessionRace) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure SPDY proxy server "proxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Fetch http://www.example.org/ through the SPDY proxy.
spdy::SpdySerializedFrame req(
spdy_util_.ConstructSpdyGet("http://www.example.org/", 1, LOWEST));
MockWrite spdy_writes[] = {CreateMockWrite(req, 0)};
spdy::SpdySerializedFrame resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame data(spdy_util_.ConstructSpdyDataFrame(1, true));
MockRead spdy_reads[] = {
CreateMockRead(resp, 1), CreateMockRead(data, 2), MockRead(ASYNC, 0, 3),
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Stall the hostname resolution begun by the transaction.
session_deps_.host_resolver->set_ondemand_mode(true);
int rv = trans.Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// Race a session to the proxy, which completes first.
session_deps_.host_resolver->set_ondemand_mode(false);
SpdySessionKey key(HostPortPair("proxy", 70), ProxyServer::Direct(),
PRIVACY_MODE_DISABLED,
SpdySessionKey::IsProxySession::kTrue, SocketTag());
base::WeakPtr<SpdySession> spdy_session =
CreateSpdySession(session.get(), key, log.bound());
// Unstall the resolution begun by the transaction.
session_deps_.host_resolver->set_ondemand_mode(true);
session_deps_.host_resolver->ResolveAllPending();
EXPECT_FALSE(callback1.have_result());
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ(kUploadData, response_data);
}
// Test a SPDY get through an HTTPS Proxy.
TEST_F(HttpNetworkTransactionTest, HttpsProxySpdyGetWithProxyAuth) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against https proxy server "myproxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// The first request will be a bare GET, the second request will be a
// GET with a Proxy-Authorization header.
spdy_util_.set_default_url(request.url);
spdy::SpdySerializedFrame req_get(
spdy_util_.ConstructSpdyGet(nullptr, 0, 1, LOWEST));
spdy_util_.UpdateWithStreamDestruction(1);
const char* const kExtraAuthorizationHeaders[] = {
"proxy-authorization", "Basic Zm9vOmJhcg=="
};
spdy::SpdySerializedFrame req_get_authorization(spdy_util_.ConstructSpdyGet(
kExtraAuthorizationHeaders, base::size(kExtraAuthorizationHeaders) / 2, 3,
LOWEST));
MockWrite spdy_writes[] = {
CreateMockWrite(req_get, 0), CreateMockWrite(req_get_authorization, 3),
};
// The first response is a 407 proxy authentication challenge, and the second
// response will be a 200 response since the second request includes a valid
// Authorization header.
const char* const kExtraAuthenticationHeaders[] = {
"proxy-authenticate", "Basic realm=\"MyRealm1\""
};
spdy::SpdySerializedFrame resp_authentication(
spdy_util_.ConstructSpdyReplyError(
"407", kExtraAuthenticationHeaders,
base::size(kExtraAuthenticationHeaders) / 2, 1));
spdy::SpdySerializedFrame body_authentication(
spdy_util_.ConstructSpdyDataFrame(1, true));
spdy::SpdySerializedFrame resp_data(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 3));
spdy::SpdySerializedFrame body_data(
spdy_util_.ConstructSpdyDataFrame(3, true));
MockRead spdy_reads[] = {
CreateMockRead(resp_authentication, 1),
CreateMockRead(body_authentication, 2, SYNCHRONOUS),
CreateMockRead(resp_data, 4),
CreateMockRead(body_data, 5),
MockRead(ASYNC, 0, 6),
};
SequencedSocketData data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* const response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(407, response->headers->response_code());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(CheckBasicSecureProxyAuth(response->auth_challenge));
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBar), callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* const response_restart = trans.GetResponseInfo();
ASSERT_TRUE(response_restart);
ASSERT_TRUE(response_restart->headers);
EXPECT_EQ(200, response_restart->headers->response_code());
// The password prompt info should not be set.
EXPECT_FALSE(response_restart->auth_challenge.has_value());
}
// Test a SPDY CONNECT through an HTTPS Proxy to an HTTPS (non-SPDY) Server.
TEST_F(HttpNetworkTransactionTest, HttpsProxySpdyConnectHttps) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against https proxy server "proxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// CONNECT to www.example.org:443 via SPDY
spdy::SpdySerializedFrame connect(spdy_util_.ConstructSpdyConnect(
nullptr, 0, 1, HttpProxyConnectJob::kH2QuicTunnelPriority,
HostPortPair("www.example.org", 443)));
// fetch https://www.example.org/ via HTTP
const char get[] =
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n";
spdy::SpdySerializedFrame wrapped_get(
spdy_util_.ConstructSpdyDataFrame(1, get, false));
spdy::SpdySerializedFrame conn_resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
const char resp[] = "HTTP/1.1 200 OK\r\n"
"Content-Length: 10\r\n\r\n";
spdy::SpdySerializedFrame wrapped_get_resp(
spdy_util_.ConstructSpdyDataFrame(1, resp, false));
spdy::SpdySerializedFrame wrapped_body(
spdy_util_.ConstructSpdyDataFrame(1, "1234567890", false));
spdy::SpdySerializedFrame window_update(
spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_get_resp.size()));
MockWrite spdy_writes[] = {
CreateMockWrite(connect, 0), CreateMockWrite(wrapped_get, 2),
CreateMockWrite(window_update, 6),
};
MockRead spdy_reads[] = {
CreateMockRead(conn_resp, 1, ASYNC),
CreateMockRead(wrapped_get_resp, 3, ASYNC),
CreateMockRead(wrapped_body, 4, ASYNC),
CreateMockRead(wrapped_body, 5, ASYNC),
MockRead(ASYNC, 0, 7),
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
SSLSocketDataProvider ssl2(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
ASSERT_THAT(rv, IsOk());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_SSL_TIMES);
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ("1234567890", response_data);
}
// Test a SPDY CONNECT through an HTTPS Proxy to a SPDY server.
TEST_F(HttpNetworkTransactionTest, HttpsProxySpdyConnectSpdy) {
SpdyTestUtil spdy_util_wrapped;
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against https proxy server "proxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// CONNECT to www.example.org:443 via SPDY
spdy::SpdySerializedFrame connect(spdy_util_.ConstructSpdyConnect(
nullptr, 0, 1, HttpProxyConnectJob::kH2QuicTunnelPriority,
HostPortPair("www.example.org", 443)));
// fetch https://www.example.org/ via SPDY
const char kMyUrl[] = "https://www.example.org/";
spdy::SpdySerializedFrame get(
spdy_util_wrapped.ConstructSpdyGet(kMyUrl, 1, LOWEST));
spdy::SpdySerializedFrame wrapped_get(
spdy_util_.ConstructWrappedSpdyFrame(get, 1));
spdy::SpdySerializedFrame conn_resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame get_resp(
spdy_util_wrapped.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame wrapped_get_resp(
spdy_util_.ConstructWrappedSpdyFrame(get_resp, 1));
spdy::SpdySerializedFrame body(
spdy_util_wrapped.ConstructSpdyDataFrame(1, true));
spdy::SpdySerializedFrame wrapped_body(
spdy_util_.ConstructWrappedSpdyFrame(body, 1));
spdy::SpdySerializedFrame window_update_get_resp(
spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_get_resp.size()));
spdy::SpdySerializedFrame window_update_body(
spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_body.size()));
MockWrite spdy_writes[] = {
CreateMockWrite(connect, 0), CreateMockWrite(wrapped_get, 2),
CreateMockWrite(window_update_get_resp, 6),
CreateMockWrite(window_update_body, 7),
};
MockRead spdy_reads[] = {
CreateMockRead(conn_resp, 1, ASYNC),
MockRead(ASYNC, ERR_IO_PENDING, 3),
CreateMockRead(wrapped_get_resp, 4, ASYNC),
CreateMockRead(wrapped_body, 5, ASYNC),
MockRead(ASYNC, 0, 8),
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
SSLSocketDataProvider ssl2(ASYNC, OK);
ssl2.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// Allow the SpdyProxyClientSocket's write callback to complete.
base::RunLoop().RunUntilIdle();
// Now allow the read of the response to complete.
spdy_data.Resume();
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_SSL_TIMES);
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ(kUploadData, response_data);
}
// Test a SPDY CONNECT failure through an HTTPS Proxy.
TEST_F(HttpNetworkTransactionTest, HttpsProxySpdyConnectFailure) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against https proxy server "proxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// CONNECT to www.example.org:443 via SPDY
spdy::SpdySerializedFrame connect(spdy_util_.ConstructSpdyConnect(
nullptr, 0, 1, HttpProxyConnectJob::kH2QuicTunnelPriority,
HostPortPair("www.example.org", 443)));
spdy::SpdySerializedFrame get(
spdy_util_.ConstructSpdyRstStream(1, spdy::ERROR_CODE_CANCEL));
MockWrite spdy_writes[] = {
CreateMockWrite(connect, 0), CreateMockWrite(get, 2),
};
spdy::SpdySerializedFrame resp(spdy_util_.ConstructSpdyReplyError(1));
spdy::SpdySerializedFrame data(spdy_util_.ConstructSpdyDataFrame(1, true));
MockRead spdy_reads[] = {
CreateMockRead(resp, 1, ASYNC), MockRead(ASYNC, 0, 3),
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
SSLSocketDataProvider ssl2(ASYNC, OK);
ssl2.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_TUNNEL_CONNECTION_FAILED));
// TODO(juliatuttle): Anything else to check here?
}
// Test the case where a proxied H2 session doesn't exist when an auth challenge
// is observed, but does exist by the time auth credentials are provided.
// Proxy-Connection: Close is used so that there's a second DNS lookup, which is
// what causes the existing H2 session to be noticed and reused.
TEST_F(HttpNetworkTransactionTest, ProxiedH2SessionAppearsDuringAuth) {
ProxyConfig proxy_config;
proxy_config.set_auto_detect(true);
proxy_config.set_pac_url(GURL("http://fooproxyurl"));
CapturingProxyResolver capturing_proxy_resolver;
capturing_proxy_resolver.set_proxy_server(
ProxyServer(ProxyServer::SCHEME_HTTP, HostPortPair("myproxy", 70)));
session_deps_.proxy_resolution_service =
std::make_unique<ProxyResolutionService>(
std::make_unique<ProxyConfigServiceFixed>(ProxyConfigWithAnnotation(
proxy_config, TRAFFIC_ANNOTATION_FOR_TESTS)),
std::make_unique<CapturingProxyResolverFactory>(
&capturing_proxy_resolver),
nullptr);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
const char kMyUrl[] = "https://www.example.org/";
spdy::SpdySerializedFrame get(spdy_util_.ConstructSpdyGet(kMyUrl, 1, LOWEST));
spdy::SpdySerializedFrame get_resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame body(spdy_util_.ConstructSpdyDataFrame(1, true));
spdy_util_.UpdateWithStreamDestruction(1);
spdy::SpdySerializedFrame get2(
spdy_util_.ConstructSpdyGet(kMyUrl, 3, LOWEST));
spdy::SpdySerializedFrame get_resp2(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 3));
spdy::SpdySerializedFrame body2(spdy_util_.ConstructSpdyDataFrame(3, true));
MockWrite auth_challenge_writes[] = {
MockWrite(ASYNC, 0,
"CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
MockRead auth_challenge_reads[] = {
MockRead(ASYNC, 1,
"HTTP/1.1 407 Authentication Required\r\n"
"Content-Length: 0\r\n"
"Proxy-Connection: close\r\n"
"Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n\r\n"),
};
MockWrite spdy_writes[] = {
MockWrite(ASYNC, 0,
"CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
CreateMockWrite(get, 2),
CreateMockWrite(get2, 5),
};
MockRead spdy_reads[] = {
MockRead(ASYNC, 1, "HTTP/1.1 200 OK\r\n\r\n"),
CreateMockRead(get_resp, 3, ASYNC),
CreateMockRead(body, 4, ASYNC),
CreateMockRead(get_resp2, 6, ASYNC),
CreateMockRead(body2, 7, ASYNC),
MockRead(SYNCHRONOUS, ERR_IO_PENDING, 8),
};
SequencedSocketData auth_challenge1(auth_challenge_reads,
auth_challenge_writes);
session_deps_.socket_factory->AddSocketDataProvider(&auth_challenge1);
SequencedSocketData auth_challenge2(auth_challenge_reads,
auth_challenge_writes);
session_deps_.socket_factory->AddSocketDataProvider(&auth_challenge2);
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback;
std::string response_data;
// Run first request until an auth challenge is observed.
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL(kMyUrl);
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans1(LOWEST, session.get());
int rv = trans1.Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans1.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(407, response->headers->response_code());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge));
// Run second request until an auth challenge is observed.
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL(kMyUrl);
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans2(LOWEST, session.get());
rv = trans2.Start(&request2, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
response = trans2.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(407, response->headers->response_code());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge));
// Now provide credentials for the first request, and wait for it to complete.
rv = trans1.RestartWithAuth(AuthCredentials(kFoo, kBar), callback.callback());
rv = callback.GetResult(rv);
EXPECT_THAT(rv, IsOk());
response = trans1.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
ASSERT_THAT(ReadTransaction(&trans1, &response_data), IsOk());
EXPECT_EQ(kUploadData, response_data);
// Now provide credentials for the second request. It should notice the
// existing session, and reuse it.
rv = trans2.RestartWithAuth(AuthCredentials(kFoo, kBar), callback.callback());
EXPECT_THAT(callback.GetResult(rv), IsOk());
response = trans2.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
ASSERT_THAT(ReadTransaction(&trans2, &response_data), IsOk());
EXPECT_EQ(kUploadData, response_data);
}
// Test load timing in the case of two HTTPS (non-SPDY) requests through a SPDY
// HTTPS Proxy to different servers.
TEST_F(HttpNetworkTransactionTest,
HttpsProxySpdyConnectHttpsLoadTimingTwoRequestsTwoServers) {
// Configure against https proxy server "proxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(
SpdySessionDependencies::SpdyCreateSession(&session_deps_));
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("https://www.example.org/");
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("https://mail.example.org/");
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// CONNECT to www.example.org:443 via SPDY.
spdy::SpdySerializedFrame connect1(spdy_util_.ConstructSpdyConnect(
nullptr, 0, 1, HttpProxyConnectJob::kH2QuicTunnelPriority,
HostPortPair("www.example.org", 443)));
spdy::SpdySerializedFrame conn_resp1(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
// Fetch https://www.example.org/ via HTTP.
const char get1[] =
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n";
spdy::SpdySerializedFrame wrapped_get1(
spdy_util_.ConstructSpdyDataFrame(1, get1, false));
const char resp1[] = "HTTP/1.1 200 OK\r\n"
"Content-Length: 1\r\n\r\n";
spdy::SpdySerializedFrame wrapped_get_resp1(
spdy_util_.ConstructSpdyDataFrame(1, resp1, false));
spdy::SpdySerializedFrame wrapped_body1(
spdy_util_.ConstructSpdyDataFrame(1, "1", false));
spdy::SpdySerializedFrame window_update(
spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_get_resp1.size()));
// CONNECT to mail.example.org:443 via SPDY.
spdy::SpdyHeaderBlock connect2_block;
connect2_block[spdy::kHttp2MethodHeader] = "CONNECT";
connect2_block[spdy::kHttp2AuthorityHeader] = "mail.example.org:443";
spdy::SpdySerializedFrame connect2(spdy_util_.ConstructSpdyHeaders(
3, std::move(connect2_block), HttpProxyConnectJob::kH2QuicTunnelPriority,
false));
spdy::SpdySerializedFrame conn_resp2(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 3));
// Fetch https://mail.example.org/ via HTTP.
const char get2[] =
"GET / HTTP/1.1\r\n"
"Host: mail.example.org\r\n"
"Connection: keep-alive\r\n\r\n";
spdy::SpdySerializedFrame wrapped_get2(
spdy_util_.ConstructSpdyDataFrame(3, get2, false));
const char resp2[] = "HTTP/1.1 200 OK\r\n"
"Content-Length: 2\r\n\r\n";
spdy::SpdySerializedFrame wrapped_get_resp2(
spdy_util_.ConstructSpdyDataFrame(3, resp2, false));
spdy::SpdySerializedFrame wrapped_body2(
spdy_util_.ConstructSpdyDataFrame(3, "22", false));
MockWrite spdy_writes[] = {
CreateMockWrite(connect1, 0), CreateMockWrite(wrapped_get1, 2),
CreateMockWrite(connect2, 5), CreateMockWrite(wrapped_get2, 7),
};
MockRead spdy_reads[] = {
CreateMockRead(conn_resp1, 1, ASYNC),
CreateMockRead(wrapped_get_resp1, 3, ASYNC),
CreateMockRead(wrapped_body1, 4, ASYNC),
CreateMockRead(conn_resp2, 6, ASYNC),
CreateMockRead(wrapped_get_resp2, 8, ASYNC),
CreateMockRead(wrapped_body2, 9, ASYNC),
MockRead(ASYNC, 0, 10),
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
SSLSocketDataProvider ssl2(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
SSLSocketDataProvider ssl3(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl3);
TestCompletionCallback callback;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_SSL_TIMES);
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
std::string response_data;
scoped_refptr<IOBuffer> buf = base::MakeRefCounted<IOBuffer>(256);
rv = trans.Read(buf.get(), 256, callback.callback());
EXPECT_EQ(1, callback.GetResult(rv));
HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
rv = trans2.Start(&request2, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
LoadTimingInfo load_timing_info2;
EXPECT_TRUE(trans2.GetLoadTimingInfo(&load_timing_info2));
// Even though the SPDY connection is reused, a new tunnelled connection has
// to be created, so the socket's load timing looks like a fresh connection.
TestLoadTimingNotReused(load_timing_info2, CONNECT_TIMING_HAS_SSL_TIMES);
// The requests should have different IDs, since they each are using their own
// separate stream.
EXPECT_NE(load_timing_info.socket_log_id, load_timing_info2.socket_log_id);
rv = trans2.Read(buf.get(), 256, callback.callback());
EXPECT_EQ(2, callback.GetResult(rv));
}
// Test load timing in the case of two HTTPS (non-SPDY) requests through a SPDY
// HTTPS Proxy to the same server.
TEST_F(HttpNetworkTransactionTest,
HttpsProxySpdyConnectHttpsLoadTimingTwoRequestsSameServer) {
// Configure against https proxy server "proxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(
SpdySessionDependencies::SpdyCreateSession(&session_deps_));
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("https://www.example.org/");
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("https://www.example.org/2");
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// CONNECT to www.example.org:443 via SPDY.
spdy::SpdySerializedFrame connect1(spdy_util_.ConstructSpdyConnect(
nullptr, 0, 1, HttpProxyConnectJob::kH2QuicTunnelPriority,
HostPortPair("www.example.org", 443)));
spdy::SpdySerializedFrame conn_resp1(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
// Fetch https://www.example.org/ via HTTP.
const char get1[] =
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n";
spdy::SpdySerializedFrame wrapped_get1(
spdy_util_.ConstructSpdyDataFrame(1, get1, false));
const char resp1[] = "HTTP/1.1 200 OK\r\n"
"Content-Length: 1\r\n\r\n";
spdy::SpdySerializedFrame wrapped_get_resp1(
spdy_util_.ConstructSpdyDataFrame(1, resp1, false));
spdy::SpdySerializedFrame wrapped_body1(
spdy_util_.ConstructSpdyDataFrame(1, "1", false));
spdy::SpdySerializedFrame window_update(
spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_get_resp1.size()));
// Fetch https://www.example.org/2 via HTTP.
const char get2[] =
"GET /2 HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n";
spdy::SpdySerializedFrame wrapped_get2(
spdy_util_.ConstructSpdyDataFrame(1, get2, false));
const char resp2[] = "HTTP/1.1 200 OK\r\n"
"Content-Length: 2\r\n\r\n";
spdy::SpdySerializedFrame wrapped_get_resp2(
spdy_util_.ConstructSpdyDataFrame(1, resp2, false));
spdy::SpdySerializedFrame wrapped_body2(
spdy_util_.ConstructSpdyDataFrame(1, "22", false));
MockWrite spdy_writes[] = {
CreateMockWrite(connect1, 0), CreateMockWrite(wrapped_get1, 2),
CreateMockWrite(wrapped_get2, 5),
};
MockRead spdy_reads[] = {
CreateMockRead(conn_resp1, 1, ASYNC),
CreateMockRead(wrapped_get_resp1, 3, ASYNC),
CreateMockRead(wrapped_body1, 4, SYNCHRONOUS),
CreateMockRead(wrapped_get_resp2, 6, ASYNC),
CreateMockRead(wrapped_body2, 7, SYNCHRONOUS),
MockRead(ASYNC, 0, 8),
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
SSLSocketDataProvider ssl2(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
TestCompletionCallback callback;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_SSL_TIMES);
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
std::string response_data;
scoped_refptr<IOBuffer> buf = base::MakeRefCounted<IOBuffer>(256);
EXPECT_EQ(1, trans->Read(buf.get(), 256, callback.callback()));
trans.reset();
auto trans2 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
rv = trans2->Start(&request2, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
LoadTimingInfo load_timing_info2;
EXPECT_TRUE(trans2->GetLoadTimingInfo(&load_timing_info2));
TestLoadTimingReused(load_timing_info2);
// The requests should have the same ID.
EXPECT_EQ(load_timing_info.socket_log_id, load_timing_info2.socket_log_id);
EXPECT_EQ(2, trans2->Read(buf.get(), 256, callback.callback()));
}
// Test load timing in the case of of two HTTP requests through a SPDY HTTPS
// Proxy to different servers.
TEST_F(HttpNetworkTransactionTest, HttpsProxySpdyLoadTimingTwoHttpRequests) {
// Configure against https proxy server "proxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(
SpdySessionDependencies::SpdyCreateSession(&session_deps_));
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("http://www.example.org/");
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("http://mail.example.org/");
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// http://www.example.org/
spdy::SpdyHeaderBlock headers(
spdy_util_.ConstructGetHeaderBlockForProxy("http://www.example.org/"));
spdy::SpdySerializedFrame get1(
spdy_util_.ConstructSpdyHeaders(1, std::move(headers), LOWEST, true));
spdy::SpdySerializedFrame get_resp1(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame body1(
spdy_util_.ConstructSpdyDataFrame(1, "1", true));
spdy_util_.UpdateWithStreamDestruction(1);
// http://mail.example.org/
spdy::SpdyHeaderBlock headers2(
spdy_util_.ConstructGetHeaderBlockForProxy("http://mail.example.org/"));
spdy::SpdySerializedFrame get2(
spdy_util_.ConstructSpdyHeaders(3, std::move(headers2), LOWEST, true));
spdy::SpdySerializedFrame get_resp2(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 3));
spdy::SpdySerializedFrame body2(
spdy_util_.ConstructSpdyDataFrame(3, "22", true));
MockWrite spdy_writes[] = {
CreateMockWrite(get1, 0), CreateMockWrite(get2, 3),
};
MockRead spdy_reads[] = {
CreateMockRead(get_resp1, 1, ASYNC),
CreateMockRead(body1, 2, ASYNC),
CreateMockRead(get_resp2, 4, ASYNC),
CreateMockRead(body2, 5, ASYNC),
MockRead(ASYNC, 0, 6),
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReused(load_timing_info,
CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
std::string response_data;
scoped_refptr<IOBuffer> buf = base::MakeRefCounted<IOBuffer>(256);
rv = trans->Read(buf.get(), 256, callback.callback());
EXPECT_EQ(1, callback.GetResult(rv));
// Delete the first request, so the second one can reuse the socket.
trans.reset();
HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
rv = trans2.Start(&request2, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
LoadTimingInfo load_timing_info2;
EXPECT_TRUE(trans2.GetLoadTimingInfo(&load_timing_info2));
TestLoadTimingReused(load_timing_info2);
// The requests should have the same ID.
EXPECT_EQ(load_timing_info.socket_log_id, load_timing_info2.socket_log_id);
rv = trans2.Read(buf.get(), 256, callback.callback());
EXPECT_EQ(2, callback.GetResult(rv));
}
// Test that an HTTP/2 CONNECT through an HTTPS Proxy to a HTTP/2 server and a
// direct (non-proxied) request to the proxy server are not pooled, as that
// would break socket pool isolation.
TEST_F(HttpNetworkTransactionTest, SpdyProxyIsolation1) {
ProxyConfig proxy_config;
proxy_config.set_auto_detect(true);
proxy_config.set_pac_url(GURL("http://fooproxyurl"));
CapturingProxyResolver capturing_proxy_resolver;
session_deps_.proxy_resolution_service =
std::make_unique<ProxyResolutionService>(
std::make_unique<ProxyConfigServiceFixed>(ProxyConfigWithAnnotation(
proxy_config, TRAFFIC_ANNOTATION_FOR_TESTS)),
std::make_unique<CapturingProxyResolverFactory>(
&capturing_proxy_resolver),
nullptr);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
SpdyTestUtil spdy_util1;
// CONNECT to www.example.org:443 via HTTP/2.
spdy::SpdySerializedFrame connect(spdy_util_.ConstructSpdyConnect(
nullptr, 0, 1, HttpProxyConnectJob::kH2QuicTunnelPriority,
HostPortPair("www.example.org", 443)));
// fetch https://www.example.org/ via HTTP/2.
const char kMyUrl[] = "https://www.example.org/";
spdy::SpdySerializedFrame get(spdy_util1.ConstructSpdyGet(kMyUrl, 1, LOWEST));
spdy::SpdySerializedFrame wrapped_get(
spdy_util_.ConstructWrappedSpdyFrame(get, 1));
spdy::SpdySerializedFrame conn_resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame get_resp(
spdy_util1.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame wrapped_get_resp(
spdy_util_.ConstructWrappedSpdyFrame(get_resp, 1));
spdy::SpdySerializedFrame body(spdy_util1.ConstructSpdyDataFrame(1, true));
spdy::SpdySerializedFrame wrapped_body(
spdy_util_.ConstructWrappedSpdyFrame(body, 1));
spdy::SpdySerializedFrame window_update_get_resp(
spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_get_resp.size()));
spdy::SpdySerializedFrame window_update_body(
spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_body.size()));
MockWrite spdy_writes1[] = {
CreateMockWrite(connect, 0),
CreateMockWrite(wrapped_get, 2),
CreateMockWrite(window_update_get_resp, 6),
CreateMockWrite(window_update_body, 7),
};
MockRead spdy_reads1[] = {
CreateMockRead(conn_resp, 1, ASYNC),
MockRead(ASYNC, ERR_IO_PENDING, 3),
CreateMockRead(wrapped_get_resp, 4, ASYNC),
CreateMockRead(wrapped_body, 5, ASYNC),
MockRead(ASYNC, 0, 8),
};
SequencedSocketData spdy_data1(spdy_reads1, spdy_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data1);
// Fetch https://proxy:70/ via HTTP/2. Needs a new SpdyTestUtil, since it uses
// a new pipe.
SpdyTestUtil spdy_util2;
spdy::SpdySerializedFrame req(
spdy_util2.ConstructSpdyGet("https://proxy:70/", 1, LOWEST));
MockWrite spdy_writes2[] = {CreateMockWrite(req, 0)};
spdy::SpdySerializedFrame resp(
spdy_util2.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame data(spdy_util2.ConstructSpdyDataFrame(1, true));
MockRead spdy_reads2[] = {
CreateMockRead(resp, 1),
CreateMockRead(data, 2),
MockRead(ASYNC, 0, 3),
};
SequencedSocketData spdy_data2(spdy_reads2, spdy_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data2);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
SSLSocketDataProvider ssl2(ASYNC, OK);
ssl2.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
SSLSocketDataProvider ssl3(ASYNC, OK);
ssl3.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl3);
TestCompletionCallback callback;
std::string response_data;
// Make a request using proxy:70 as a HTTP/2 proxy.
capturing_proxy_resolver.set_proxy_server(
ProxyServer(ProxyServer::SCHEME_HTTPS, HostPortPair("proxy", 70)));
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("https://www.example.org/");
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans1(LOWEST, session.get());
int rv = trans1.Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// Allow the SpdyProxyClientSocket's write callback to complete.
base::RunLoop().RunUntilIdle();
// Now allow the read of the response to complete.
spdy_data1.Resume();
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans1.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
ASSERT_THAT(ReadTransaction(&trans1, &response_data), IsOk());
EXPECT_EQ(kUploadData, response_data);
RunUntilIdle();
// Make a direct HTTP/2 request to proxy:70.
capturing_proxy_resolver.set_proxy_server(ProxyServer::Direct());
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("https://proxy:70/");
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans2(LOWEST, session.get());
EXPECT_THAT(callback.GetResult(trans2.Start(&request2, callback.callback(),
NetLogWithSource())),
IsOk());
ASSERT_THAT(ReadTransaction(&trans2, &response_data), IsOk());
}
// Same as above, but reverse request order, since the code to check for an
// existing session is different for tunnels and direct connections.
TEST_F(HttpNetworkTransactionTest, SpdyProxyIsolation2) {
// Configure against https proxy server "myproxy:80".
ProxyConfig proxy_config;
proxy_config.set_auto_detect(true);
proxy_config.set_pac_url(GURL("http://fooproxyurl"));
CapturingProxyResolver capturing_proxy_resolver;
session_deps_.proxy_resolution_service =
std::make_unique<ProxyResolutionService>(
std::make_unique<ProxyConfigServiceFixed>(ProxyConfigWithAnnotation(
proxy_config, TRAFFIC_ANNOTATION_FOR_TESTS)),
std::make_unique<CapturingProxyResolverFactory>(
&capturing_proxy_resolver),
nullptr);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Fetch https://proxy:70/ via HTTP/2.
SpdyTestUtil spdy_util1;
spdy::SpdySerializedFrame req(
spdy_util1.ConstructSpdyGet("https://proxy:70/", 1, LOWEST));
MockWrite spdy_writes1[] = {CreateMockWrite(req, 0)};
spdy::SpdySerializedFrame resp(
spdy_util1.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame data(spdy_util1.ConstructSpdyDataFrame(1, true));
MockRead spdy_reads1[] = {
CreateMockRead(resp, 1),
CreateMockRead(data, 2),
MockRead(ASYNC, 0, 3),
};
SequencedSocketData spdy_data1(spdy_reads1, spdy_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data1);
SpdyTestUtil spdy_util2;
// CONNECT to www.example.org:443 via HTTP/2.
spdy::SpdySerializedFrame connect(spdy_util_.ConstructSpdyConnect(
nullptr, 0, 1, HttpProxyConnectJob::kH2QuicTunnelPriority,
HostPortPair("www.example.org", 443)));
// fetch https://www.example.org/ via HTTP/2.
const char kMyUrl[] = "https://www.example.org/";
spdy::SpdySerializedFrame get(spdy_util2.ConstructSpdyGet(kMyUrl, 1, LOWEST));
spdy::SpdySerializedFrame wrapped_get(
spdy_util_.ConstructWrappedSpdyFrame(get, 1));
spdy::SpdySerializedFrame conn_resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame get_resp(
spdy_util2.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame wrapped_get_resp(
spdy_util_.ConstructWrappedSpdyFrame(get_resp, 1));
spdy::SpdySerializedFrame body(spdy_util2.ConstructSpdyDataFrame(1, true));
spdy::SpdySerializedFrame wrapped_body(
spdy_util_.ConstructWrappedSpdyFrame(body, 1));
spdy::SpdySerializedFrame window_update_get_resp(
spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_get_resp.size()));
spdy::SpdySerializedFrame window_update_body(
spdy_util_.ConstructSpdyWindowUpdate(1, wrapped_body.size()));
MockWrite spdy_writes2[] = {
CreateMockWrite(connect, 0),
CreateMockWrite(wrapped_get, 2),
CreateMockWrite(window_update_get_resp, 6),
CreateMockWrite(window_update_body, 7),
};
MockRead spdy_reads2[] = {
CreateMockRead(conn_resp, 1, ASYNC),
MockRead(ASYNC, ERR_IO_PENDING, 3),
CreateMockRead(wrapped_get_resp, 4, ASYNC),
CreateMockRead(wrapped_body, 5, ASYNC),
MockRead(ASYNC, 0, 8),
};
SequencedSocketData spdy_data2(spdy_reads2, spdy_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data2);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
SSLSocketDataProvider ssl2(ASYNC, OK);
ssl2.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
SSLSocketDataProvider ssl3(ASYNC, OK);
ssl3.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl3);
TestCompletionCallback callback;
std::string response_data;
// Make a direct HTTP/2 request to proxy:70.
capturing_proxy_resolver.set_proxy_server(ProxyServer::Direct());
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("https://proxy:70/");
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans1(LOWEST, session.get());
EXPECT_THAT(callback.GetResult(trans1.Start(&request1, callback.callback(),
NetLogWithSource())),
IsOk());
ASSERT_THAT(ReadTransaction(&trans1, &response_data), IsOk());
RunUntilIdle();
// Make a request using proxy:70 as a HTTP/2 proxy.
capturing_proxy_resolver.set_proxy_server(
ProxyServer(ProxyServer::SCHEME_HTTPS, HostPortPair("proxy", 70)));
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("https://www.example.org/");
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans2(LOWEST, session.get());
int rv = trans2.Start(&request2, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// Allow the SpdyProxyClientSocket's write callback to complete.
base::RunLoop().RunUntilIdle();
// Now allow the read of the response to complete.
spdy_data2.Resume();
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response2 = trans2.GetResponseInfo();
ASSERT_TRUE(response2);
ASSERT_TRUE(response2->headers);
EXPECT_EQ("HTTP/1.1 200", response2->headers->GetStatusLine());
ASSERT_THAT(ReadTransaction(&trans2, &response_data), IsOk());
EXPECT_EQ(kUploadData, response_data);
}
// Test the challenge-response-retry sequence through an HTTPS Proxy
TEST_F(HttpNetworkTransactionTest, HttpsProxyAuthRetry) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
// when the no authentication data flag is set.
request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against https proxy server "myproxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Since we have proxy, should use full url
MockWrite data_writes1[] = {
MockWrite("GET http://www.example.org/ HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
// After calling trans.RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite("GET http://www.example.org/ HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
// The proxy responds to the GET with a 407, using a persistent
// connection.
MockRead data_reads1[] = {
// No credentials.
MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Proxy-Connection: keep-alive\r\n"),
MockRead("Content-Length: 0\r\n\r\n"),
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReused(load_timing_info,
CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(407, response->headers->response_code());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
EXPECT_TRUE(CheckBasicSecureProxyAuth(response->auth_challenge));
EXPECT_FALSE(response->did_use_http_auth);
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBar), callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
load_timing_info = LoadTimingInfo();
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
// Retrying with HTTP AUTH is considered to be reusing a socket.
TestLoadTimingReused(load_timing_info);
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(100, response->headers->GetContentLength());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
EXPECT_TRUE(response->did_use_http_auth);
// The password prompt info should not be set.
EXPECT_FALSE(response->auth_challenge.has_value());
}
void HttpNetworkTransactionTest::ConnectStatusHelperWithExpectedStatus(
const MockRead& status, int expected_status) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
status, MockRead("Content-Length: 10\r\n\r\n"),
// No response body because the test stops reading here.
MockRead(SYNCHRONOUS, ERR_UNEXPECTED),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_EQ(expected_status, rv);
}
void HttpNetworkTransactionTest::ConnectStatusHelper(
const MockRead& status) {
ConnectStatusHelperWithExpectedStatus(
status, ERR_TUNNEL_CONNECTION_FAILED);
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus100) {
ConnectStatusHelper(MockRead("HTTP/1.1 100 Continue\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus101) {
ConnectStatusHelper(MockRead("HTTP/1.1 101 Switching Protocols\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus201) {
ConnectStatusHelper(MockRead("HTTP/1.1 201 Created\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus202) {
ConnectStatusHelper(MockRead("HTTP/1.1 202 Accepted\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus203) {
ConnectStatusHelper(
MockRead("HTTP/1.1 203 Non-Authoritative Information\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus204) {
ConnectStatusHelper(MockRead("HTTP/1.1 204 No Content\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus205) {
ConnectStatusHelper(MockRead("HTTP/1.1 205 Reset Content\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus206) {
ConnectStatusHelper(MockRead("HTTP/1.1 206 Partial Content\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus300) {
ConnectStatusHelper(MockRead("HTTP/1.1 300 Multiple Choices\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus301) {
ConnectStatusHelper(MockRead("HTTP/1.1 301 Moved Permanently\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus302) {
ConnectStatusHelper(MockRead("HTTP/1.1 302 Found\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus303) {
ConnectStatusHelper(MockRead("HTTP/1.1 303 See Other\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus304) {
ConnectStatusHelper(MockRead("HTTP/1.1 304 Not Modified\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus305) {
ConnectStatusHelper(MockRead("HTTP/1.1 305 Use Proxy\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus306) {
ConnectStatusHelper(MockRead("HTTP/1.1 306\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus307) {
ConnectStatusHelper(MockRead("HTTP/1.1 307 Temporary Redirect\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus308) {
ConnectStatusHelper(MockRead("HTTP/1.1 308 Permanent Redirect\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus400) {
ConnectStatusHelper(MockRead("HTTP/1.1 400 Bad Request\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus401) {
ConnectStatusHelper(MockRead("HTTP/1.1 401 Unauthorized\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus402) {
ConnectStatusHelper(MockRead("HTTP/1.1 402 Payment Required\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus403) {
ConnectStatusHelper(MockRead("HTTP/1.1 403 Forbidden\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus404) {
ConnectStatusHelper(MockRead("HTTP/1.1 404 Not Found\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus405) {
ConnectStatusHelper(MockRead("HTTP/1.1 405 Method Not Allowed\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus406) {
ConnectStatusHelper(MockRead("HTTP/1.1 406 Not Acceptable\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus407) {
ConnectStatusHelperWithExpectedStatus(
MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
ERR_PROXY_AUTH_UNSUPPORTED);
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus408) {
ConnectStatusHelper(MockRead("HTTP/1.1 408 Request Timeout\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus409) {
ConnectStatusHelper(MockRead("HTTP/1.1 409 Conflict\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus410) {
ConnectStatusHelper(MockRead("HTTP/1.1 410 Gone\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus411) {
ConnectStatusHelper(MockRead("HTTP/1.1 411 Length Required\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus412) {
ConnectStatusHelper(MockRead("HTTP/1.1 412 Precondition Failed\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus413) {
ConnectStatusHelper(MockRead("HTTP/1.1 413 Request Entity Too Large\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus414) {
ConnectStatusHelper(MockRead("HTTP/1.1 414 Request-URI Too Long\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus415) {
ConnectStatusHelper(MockRead("HTTP/1.1 415 Unsupported Media Type\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus416) {
ConnectStatusHelper(
MockRead("HTTP/1.1 416 Requested Range Not Satisfiable\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus417) {
ConnectStatusHelper(MockRead("HTTP/1.1 417 Expectation Failed\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus500) {
ConnectStatusHelper(MockRead("HTTP/1.1 500 Internal Server Error\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus501) {
ConnectStatusHelper(MockRead("HTTP/1.1 501 Not Implemented\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus502) {
ConnectStatusHelper(MockRead("HTTP/1.1 502 Bad Gateway\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus503) {
ConnectStatusHelper(MockRead("HTTP/1.1 503 Service Unavailable\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus504) {
ConnectStatusHelper(MockRead("HTTP/1.1 504 Gateway Timeout\r\n"));
}
TEST_F(HttpNetworkTransactionTest, ConnectStatus505) {
ConnectStatusHelper(MockRead("HTTP/1.1 505 HTTP Version Not Supported\r\n"));
}
// Test the flow when both the proxy server AND origin server require
// authentication. Again, this uses basic auth for both since that is
// the simplest to mock.
TEST_F(HttpNetworkTransactionTest, BasicAuthProxyThenServer) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes1[] = {
MockWrite(
"GET http://www.example.org/ HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.0 407 Unauthorized\r\n"),
// Give a couple authenticate options (only the middle one is actually
// supported).
MockRead("Proxy-Authenticate: Basic invalid\r\n"), // Malformed.
MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Proxy-Authenticate: UNSUPPORTED realm=\"FOO\"\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
// Large content-length -- won't matter, as connection will be reset.
MockRead("Content-Length: 10000\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED),
};
// After calling trans.RestartWithAuth() the first time, this is the
// request we should be issuing -- the final header line contains the
// proxy's credentials.
MockWrite data_writes2[] = {
MockWrite(
"GET http://www.example.org/ HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
// Now the proxy server lets the request pass through to origin server.
// The origin server responds with a 401.
MockRead data_reads2[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
// Note: We are using the same realm-name as the proxy server. This is
// completely valid, as realms are unique across hosts.
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 2000\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED), // Won't be reached.
};
// After calling trans.RestartWithAuth() the second time, we should send
// the credentials for both the proxy and origin server.
MockWrite data_writes3[] = {
MockWrite(
"GET http://www.example.org/ HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: Basic Zm9vOmJhcg==\r\n"
"Authorization: Basic Zm9vMjpiYXIy\r\n\r\n"),
};
// Lastly we get the desired content.
MockRead data_reads3[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
StaticSocketDataProvider data3(data_reads3, data_writes3);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
session_deps_.socket_factory->AddSocketDataProvider(&data3);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckBasicProxyAuth(response->auth_challenge));
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBar), callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge));
TestCompletionCallback callback3;
rv = trans.RestartWithAuth(AuthCredentials(kFoo2, kBar2),
callback3.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback3.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(100, response->headers->GetContentLength());
}
// For the NTLM implementation using SSPI, we skip the NTLM tests since we
// can't hook into its internals to cause it to generate predictable NTLM
// authorization headers.
#if defined(NTLM_PORTABLE)
// The NTLM authentication unit tests are based on known test data from the
// [MS-NLMP] Specification [1]. These tests are primarily of the authentication
// flow rather than the implementation of the NTLM protocol. See net/ntlm
// for the implementation and testing of the protocol.
//
// [1] https://msdn.microsoft.com/en-us/library/cc236621.aspx
// Enter the correct password and authenticate successfully.
TEST_F(HttpNetworkTransactionTest, NTLMAuthV2) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://server/kids/login.aspx");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Ensure load is not disrupted by flags which suppress behaviour specific
// to other auth schemes.
request.load_flags = LOAD_DO_NOT_USE_EMBEDDED_IDENTITY;
HttpAuthHandlerNTLM::ScopedProcSetter proc_setter(
MockGetMSTime, MockGenerateRandom, MockGetHostName);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Generate the NTLM messages based on known test data.
std::string negotiate_msg;
std::string challenge_msg;
std::string authenticate_msg;
base::Base64Encode(
base::StringPiece(
reinterpret_cast<const char*>(ntlm::test::kExpectedNegotiateMsg),
base::size(ntlm::test::kExpectedNegotiateMsg)),
&negotiate_msg);
base::Base64Encode(
base::StringPiece(
reinterpret_cast<const char*>(ntlm::test::kChallengeMsgFromSpecV2),
base::size(ntlm::test::kChallengeMsgFromSpecV2)),
&challenge_msg);
base::Base64Encode(
base::StringPiece(
reinterpret_cast<const char*>(
ntlm::test::kExpectedAuthenticateMsgEmptyChannelBindingsV2),
base::size(
ntlm::test::kExpectedAuthenticateMsgEmptyChannelBindingsV2)),
&authenticate_msg);
MockWrite data_writes1[] = {
MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
"Host: server\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 401 Access Denied\r\n"),
// Negotiate and NTLM are often requested together. However, we only want
// to test NTLM. Since Negotiate is preferred over NTLM, we have to skip
// the header that requests Negotiate for this test.
MockRead("WWW-Authenticate: NTLM\r\n"),
MockRead("Connection: close\r\n"),
MockRead("Content-Length: 42\r\n"),
MockRead("Content-Type: text/html\r\n\r\n"),
// Missing content -- won't matter, as connection will be reset.
};
MockWrite data_writes2[] = {
// After restarting with a null identity, this is the
// request we should be issuing -- the final header line contains a Type
// 1 message.
MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
"Host: server\r\n"
"Connection: keep-alive\r\n"
"Authorization: NTLM "),
MockWrite(negotiate_msg.c_str()), MockWrite("\r\n\r\n"),
// After calling trans.RestartWithAuth(), we should send a Type 3 message
// (using correct credentials). The second request continues on the
// same connection.
MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
"Host: server\r\n"
"Connection: keep-alive\r\n"
"Authorization: NTLM "),
MockWrite(authenticate_msg.c_str()), MockWrite("\r\n\r\n"),
};
MockRead data_reads2[] = {
// The origin server responds with a Type 2 message.
MockRead("HTTP/1.1 401 Access Denied\r\n"),
MockRead("WWW-Authenticate: NTLM "), MockRead(challenge_msg.c_str()),
MockRead("\r\n"), MockRead("Content-Length: 42\r\n"),
MockRead("Content-Type: text/html\r\n\r\n"),
MockRead("You are not authorized to view this page\r\n"),
// Lastly we get the desired content.
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=utf-8\r\n"),
MockRead("Content-Length: 14\r\n\r\n"), MockRead("Please Login\r\n"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
SSLSocketDataProvider ssl1(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
SSLSocketDataProvider ssl2(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_FALSE(trans.IsReadyToRestartForAuth());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckNTLMServerAuth(response->auth_challenge));
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(
AuthCredentials(ntlm::test::kDomainUserCombined, ntlm::test::kPassword),
callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(trans.IsReadyToRestartForAuth());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
TestCompletionCallback callback3;
rv = trans.RestartWithAuth(AuthCredentials(), callback3.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback3.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(14, response->headers->GetContentLength());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("Please Login\r\n", response_data);
EXPECT_TRUE(data1.AllReadDataConsumed());
EXPECT_TRUE(data1.AllWriteDataConsumed());
EXPECT_TRUE(data2.AllReadDataConsumed());
EXPECT_TRUE(data2.AllWriteDataConsumed());
}
// Enter a wrong password, and then the correct one.
TEST_F(HttpNetworkTransactionTest, NTLMAuthV2WrongThenRightPassword) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://server/kids/login.aspx");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpAuthHandlerNTLM::ScopedProcSetter proc_setter(
MockGetMSTime, MockGenerateRandom, MockGetHostName);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Generate the NTLM messages based on known test data.
std::string negotiate_msg;
std::string challenge_msg;
std::string authenticate_msg;
base::Base64Encode(
base::StringPiece(
reinterpret_cast<const char*>(ntlm::test::kExpectedNegotiateMsg),
base::size(ntlm::test::kExpectedNegotiateMsg)),
&negotiate_msg);
base::Base64Encode(
base::StringPiece(
reinterpret_cast<const char*>(ntlm::test::kChallengeMsgFromSpecV2),
base::size(ntlm::test::kChallengeMsgFromSpecV2)),
&challenge_msg);
base::Base64Encode(
base::StringPiece(
reinterpret_cast<const char*>(
ntlm::test::kExpectedAuthenticateMsgEmptyChannelBindingsV2),
base::size(
ntlm::test::kExpectedAuthenticateMsgEmptyChannelBindingsV2)),
&authenticate_msg);
// The authenticate message when |kWrongPassword| is sent.
std::string wrong_password_authenticate_msg(
"TlRMTVNTUAADAAAAGAAYAFgAAACKAIoAcAAAAAwADAD6AAAACAAIAAYBAAAQABAADgEAAAAA"
"AABYAAAAA4IIAAAAAAAAAAAAAPknEYqtJQtusopDRSfYzAAAAAAAAAAAAAAAAAAAAAAAAAAA"
"AAAAAOtVz38osnFdRRggUQHUJ3EBAQAAAAAAAIALyP0A1NIBqqqqqqqqqqoAAAAAAgAMAEQA"
"bwBtAGEAaQBuAAEADABTAGUAcgB2AGUAcgAGAAQAAgAAAAoAEAAAAAAAAAAAAAAAAAAAAAAA"
"CQAWAEgAVABUAFAALwBzAGUAcgB2AGUAcgAAAAAAAAAAAEQAbwBtAGEAaQBuAFUAcwBlAHIA"
"QwBPAE0AUABVAFQARQBSAA==");
// Sanity check that it's the same length as the correct authenticate message
// and that it's different.
ASSERT_EQ(authenticate_msg.length(),
wrong_password_authenticate_msg.length());
ASSERT_NE(authenticate_msg, wrong_password_authenticate_msg);
MockWrite data_writes1[] = {
MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
"Host: server\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 401 Access Denied\r\n"),
// Negotiate and NTLM are often requested together. However, we only want
// to test NTLM. Since Negotiate is preferred over NTLM, we have to skip
// the header that requests Negotiate for this test.
MockRead("WWW-Authenticate: NTLM\r\n"),
MockRead("Connection: close\r\n"),
MockRead("Content-Length: 42\r\n"),
MockRead("Content-Type: text/html\r\n\r\n"),
// Missing content -- won't matter, as connection will be reset.
};
MockWrite data_writes2[] = {
// After restarting with a null identity, this is the
// request we should be issuing -- the final header line contains a Type
// 1 message.
MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
"Host: server\r\n"
"Connection: keep-alive\r\n"
"Authorization: NTLM "),
MockWrite(negotiate_msg.c_str()), MockWrite("\r\n\r\n"),
// After calling trans.RestartWithAuth(), we should send a Type 3 message
// (using incorrect credentials). The second request continues on the
// same connection.
MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
"Host: server\r\n"
"Connection: keep-alive\r\n"
"Authorization: NTLM "),
MockWrite(wrong_password_authenticate_msg.c_str()), MockWrite("\r\n\r\n"),
};
MockRead data_reads2[] = {
// The origin server responds with a Type 2 message.
MockRead("HTTP/1.1 401 Access Denied\r\n"),
MockRead("WWW-Authenticate: NTLM "), MockRead(challenge_msg.c_str()),
MockRead("\r\n"), MockRead("Content-Length: 42\r\n"),
MockRead("Content-Type: text/html\r\n\r\n"),
MockRead("You are not authorized to view this page\r\n"),
// Wrong password.
MockRead("HTTP/1.1 401 Access Denied\r\n"),
MockRead("WWW-Authenticate: NTLM\r\n"), MockRead("Connection: close\r\n"),
MockRead("Content-Length: 42\r\n"),
MockRead("Content-Type: text/html\r\n\r\n"),
// Missing content -- won't matter, as connection will be reset.
};
MockWrite data_writes3[] = {
// After restarting with a null identity, this is the
// request we should be issuing -- the final header line contains a Type
// 1 message.
MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
"Host: server\r\n"
"Connection: keep-alive\r\n"
"Authorization: NTLM "),
MockWrite(negotiate_msg.c_str()), MockWrite("\r\n\r\n"),
// After calling trans.RestartWithAuth(), we should send a Type 3 message
// (the credentials for the origin server). The second request continues
// on the same connection.
MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
"Host: server\r\n"
"Connection: keep-alive\r\n"
"Authorization: NTLM "),
MockWrite(authenticate_msg.c_str()), MockWrite("\r\n\r\n"),
};
MockRead data_reads3[] = {
// The origin server responds with a Type 2 message.
MockRead("HTTP/1.1 401 Access Denied\r\n"),
MockRead("WWW-Authenticate: NTLM "), MockRead(challenge_msg.c_str()),
MockRead("\r\n"), MockRead("Content-Length: 42\r\n"),
MockRead("Content-Type: text/html\r\n\r\n"),
MockRead("You are not authorized to view this page\r\n"),
// Lastly we get the desired content.
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=utf-8\r\n"),
MockRead("Content-Length: 14\r\n\r\n"), MockRead("Please Login\r\n"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
StaticSocketDataProvider data3(data_reads3, data_writes3);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
session_deps_.socket_factory->AddSocketDataProvider(&data3);
SSLSocketDataProvider ssl1(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
SSLSocketDataProvider ssl2(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
SSLSocketDataProvider ssl3(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl3);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_FALSE(trans.IsReadyToRestartForAuth());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckNTLMServerAuth(response->auth_challenge));
TestCompletionCallback callback2;
// Enter the wrong password.
rv = trans.RestartWithAuth(
AuthCredentials(ntlm::test::kDomainUserCombined, kWrongPassword),
callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(trans.IsReadyToRestartForAuth());
TestCompletionCallback callback3;
rv = trans.RestartWithAuth(AuthCredentials(), callback3.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback3.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_FALSE(trans.IsReadyToRestartForAuth());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckNTLMServerAuth(response->auth_challenge));
TestCompletionCallback callback4;
// Now enter the right password.
rv = trans.RestartWithAuth(
AuthCredentials(ntlm::test::kDomainUserCombined, ntlm::test::kPassword),
callback4.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback4.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(trans.IsReadyToRestartForAuth());
TestCompletionCallback callback5;
// One more roundtrip
rv = trans.RestartWithAuth(AuthCredentials(), callback5.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback5.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(14, response->headers->GetContentLength());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("Please Login\r\n", response_data);
EXPECT_TRUE(data1.AllReadDataConsumed());
EXPECT_TRUE(data1.AllWriteDataConsumed());
EXPECT_TRUE(data2.AllReadDataConsumed());
EXPECT_TRUE(data2.AllWriteDataConsumed());
EXPECT_TRUE(data3.AllReadDataConsumed());
EXPECT_TRUE(data3.AllWriteDataConsumed());
}
// Server requests NTLM authentication, which is not supported over HTTP/2.
// Subsequent request with authorization header should be sent over HTTP/1.1.
TEST_F(HttpNetworkTransactionTest, NTLMOverHttp2) {
HttpAuthHandlerNTLM::ScopedProcSetter proc_setter(
MockGetMSTime, MockGenerateRandom, MockGetHostName);
const char* kUrl = "https://server/kids/login.aspx";
HttpRequestInfo request;
request.method = "GET";
request.url = GURL(kUrl);
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// First request without credentials.
spdy::SpdyHeaderBlock request_headers0(
spdy_util_.ConstructGetHeaderBlock(kUrl));
spdy::SpdySerializedFrame request0(spdy_util_.ConstructSpdyHeaders(
1, std::move(request_headers0), LOWEST, true));
spdy::SpdyHeaderBlock response_headers0;
response_headers0[spdy::kHttp2StatusHeader] = "401";
response_headers0["www-authenticate"] = "NTLM";
spdy::SpdySerializedFrame resp(spdy_util_.ConstructSpdyResponseHeaders(
1, std::move(response_headers0), true));
// Stream 1 is closed.
spdy_util_.UpdateWithStreamDestruction(1);
// Generate the NTLM messages based on known test data.
std::string negotiate_msg;
std::string challenge_msg;
std::string authenticate_msg;
base::Base64Encode(
base::StringPiece(
reinterpret_cast<const char*>(ntlm::test::kExpectedNegotiateMsg),
base::size(ntlm::test::kExpectedNegotiateMsg)),
&negotiate_msg);
base::Base64Encode(
base::StringPiece(
reinterpret_cast<const char*>(ntlm::test::kChallengeMsgFromSpecV2),
base::size(ntlm::test::kChallengeMsgFromSpecV2)),
&challenge_msg);
base::Base64Encode(
base::StringPiece(
reinterpret_cast<const char*>(
ntlm::test::kExpectedAuthenticateMsgEmptyChannelBindingsV2),
base::size(
ntlm::test::kExpectedAuthenticateMsgEmptyChannelBindingsV2)),
&authenticate_msg);
// Retry with authorization header.
spdy::SpdyHeaderBlock request_headers1(
spdy_util_.ConstructGetHeaderBlock(kUrl));
request_headers1["authorization"] = std::string("NTLM ") + negotiate_msg;
spdy::SpdySerializedFrame request1(spdy_util_.ConstructSpdyHeaders(
3, std::move(request_headers1), LOWEST, true));
spdy::SpdySerializedFrame rst(
spdy_util_.ConstructSpdyRstStream(3, spdy::ERROR_CODE_HTTP_1_1_REQUIRED));
MockWrite writes0[] = {CreateMockWrite(request0, 0)};
MockRead reads0[] = {CreateMockRead(resp, 1), MockRead(ASYNC, 0, 2)};
// Retry yet again using HTTP/1.1.
MockWrite writes1[] = {
// After restarting with a null identity, this is the
// request we should be issuing -- the final header line contains a Type
// 1 message.
MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
"Host: server\r\n"
"Connection: keep-alive\r\n"
"Authorization: NTLM "),
MockWrite(negotiate_msg.c_str()), MockWrite("\r\n\r\n"),
// After calling trans.RestartWithAuth(), we should send a Type 3 message
// (the credentials for the origin server). The second request continues
// on the same connection.
MockWrite("GET /kids/login.aspx HTTP/1.1\r\n"
"Host: server\r\n"
"Connection: keep-alive\r\n"
"Authorization: NTLM "),
MockWrite(authenticate_msg.c_str()), MockWrite("\r\n\r\n"),
};
MockRead reads1[] = {
// The origin server responds with a Type 2 message.
MockRead("HTTP/1.1 401 Access Denied\r\n"),
MockRead("WWW-Authenticate: NTLM "), MockRead(challenge_msg.c_str()),
MockRead("\r\n"), MockRead("Content-Length: 42\r\n"),
MockRead("Content-Type: text/html\r\n\r\n"),
MockRead("You are not authorized to view this page\r\n"),
// Lastly we get the desired content.
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=utf-8\r\n"),
MockRead("Content-Length: 14\r\n\r\n"), MockRead("Please Login\r\n"),
};
SequencedSocketData data0(reads0, writes0);
StaticSocketDataProvider data1(reads1, writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data0);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
SSLSocketDataProvider ssl0(ASYNC, OK);
ssl0.next_proto = kProtoHTTP2;
SSLSocketDataProvider ssl1(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl0);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_FALSE(trans.IsReadyToRestartForAuth());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckNTLMServerAuth(response->auth_challenge));
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(
AuthCredentials(ntlm::test::kDomainUserCombined, ntlm::test::kPassword),
callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(trans.IsReadyToRestartForAuth());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
TestCompletionCallback callback3;
rv = trans.RestartWithAuth(AuthCredentials(), callback3.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback3.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(14, response->headers->GetContentLength());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("Please Login\r\n", response_data);
EXPECT_TRUE(data0.AllReadDataConsumed());
EXPECT_TRUE(data0.AllWriteDataConsumed());
EXPECT_TRUE(data1.AllReadDataConsumed());
EXPECT_TRUE(data1.AllWriteDataConsumed());
}
// Test that, if we have an NTLM proxy and the origin resets the connection, we
// do no retry forever checking for TLS version interference. This is a
// regression test for https://crbug.com/823387. The version interference probe
// has since been removed, but retain the regression test so we can update it if
// we add future TLS retries.
TEST_F(HttpNetworkTransactionTest, NTLMProxyTLSHandshakeReset) {
// The NTLM test data expects the proxy to be named 'server'. The origin is
// https://origin/.
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY server", TRAFFIC_ANNOTATION_FOR_TESTS);
SSLConfig config;
session_deps_.ssl_config_service =
std::make_unique<TestSSLConfigService>(config);
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://origin/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Ensure load is not disrupted by flags which suppress behaviour specific
// to other auth schemes.
request.load_flags = LOAD_DO_NOT_USE_EMBEDDED_IDENTITY;
HttpAuthHandlerNTLM::ScopedProcSetter proc_setter(
MockGetMSTime, MockGenerateRandom, MockGetHostName);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Generate the NTLM messages based on known test data.
std::string negotiate_msg;
std::string challenge_msg;
std::string authenticate_msg;
base::Base64Encode(
base::StringPiece(
reinterpret_cast<const char*>(ntlm::test::kExpectedNegotiateMsg),
base::size(ntlm::test::kExpectedNegotiateMsg)),
&negotiate_msg);
base::Base64Encode(
base::StringPiece(
reinterpret_cast<const char*>(ntlm::test::kChallengeMsgFromSpecV2),
base::size(ntlm::test::kChallengeMsgFromSpecV2)),
&challenge_msg);
base::Base64Encode(
base::StringPiece(
reinterpret_cast<const char*>(
ntlm::test::kExpectedAuthenticateMsgEmptyChannelBindingsV2),
base::size(
ntlm::test::kExpectedAuthenticateMsgEmptyChannelBindingsV2)),
&authenticate_msg);
MockWrite data_writes[] = {
// The initial CONNECT request.
MockWrite("CONNECT origin:443 HTTP/1.1\r\n"
"Host: origin:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
// After restarting with an identity.
MockWrite("CONNECT origin:443 HTTP/1.1\r\n"
"Host: origin:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: NTLM "),
MockWrite(negotiate_msg.c_str()),
// End headers.
MockWrite("\r\n\r\n"),
// The second restart.
MockWrite("CONNECT origin:443 HTTP/1.1\r\n"
"Host: origin:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: NTLM "),
MockWrite(authenticate_msg.c_str()),
// End headers.
MockWrite("\r\n\r\n"),
};
MockRead data_reads[] = {
// The initial NTLM response.
MockRead("HTTP/1.1 407 Access Denied\r\n"
"Content-Length: 0\r\n"
"Proxy-Authenticate: NTLM\r\n\r\n"),
// The NTLM challenge message.
MockRead("HTTP/1.1 407 Access Denied\r\n"
"Content-Length: 0\r\n"
"Proxy-Authenticate: NTLM "),
MockRead(challenge_msg.c_str()),
// End headers.
MockRead("\r\n\r\n"),
// Finally the tunnel is established.
MockRead("HTTP/1.1 200 Connected\r\n\r\n"),
};
StaticSocketDataProvider data(data_reads, data_writes);
SSLSocketDataProvider data_ssl(ASYNC, ERR_CONNECTION_RESET);
session_deps_.socket_factory->AddSocketDataProvider(&data);
session_deps_.socket_factory->AddSSLSocketDataProvider(&data_ssl);
// Start the transaction. The proxy responds with an NTLM authentication
// request.
TestCompletionCallback callback;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = callback.GetResult(
trans.Start(&request, callback.callback(), NetLogWithSource()));
EXPECT_THAT(rv, IsOk());
EXPECT_FALSE(trans.IsReadyToRestartForAuth());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckNTLMProxyAuth(response->auth_challenge));
// Configure credentials and restart. The proxy responds with the challenge
// message.
rv = callback.GetResult(trans.RestartWithAuth(
AuthCredentials(ntlm::test::kDomainUserCombined, ntlm::test::kPassword),
callback.callback()));
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(trans.IsReadyToRestartForAuth());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
// Restart once more. The tunnel will be established and then the SSL
// handshake will reset.
rv = callback.GetResult(
trans.RestartWithAuth(AuthCredentials(), callback.callback()));
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
}
#endif // NTLM_PORTABLE
// Test reading a server response which has only headers, and no body.
// After some maximum number of bytes is consumed, the transaction should
// fail with ERR_RESPONSE_HEADERS_TOO_BIG.
TEST_F(HttpNetworkTransactionTest, LargeHeadersNoBody) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Respond with 300 kb of headers (we should fail after 256 kb).
std::string large_headers_string;
FillLargeHeadersString(&large_headers_string, 300 * 1024);
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead(ASYNC, large_headers_string.data(), large_headers_string.size()),
MockRead("\r\nBODY"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_RESPONSE_HEADERS_TOO_BIG));
}
// Make sure that we don't try to reuse a TCPClientSocket when failing to
// establish tunnel.
// http://code.google.com/p/chromium/issues/detail?id=3772
TEST_F(HttpNetworkTransactionTest, DontRecycleTransportSocketForSSLTunnel) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
// The proxy responds to the connect with a 404, using a persistent
// connection. Usually a proxy would return 501 (not implemented),
// or 200 (tunnel established).
MockRead data_reads1[] = {
MockRead("HTTP/1.1 404 Not Found\r\n"),
MockRead("Content-Length: 10\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_UNEXPECTED),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
TestCompletionCallback callback1;
int rv = trans->Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_TUNNEL_CONNECTION_FAILED));
// Empty the current queue. This is necessary because idle sockets are
// added to the connection pool asynchronously with a PostTask.
base::RunLoop().RunUntilIdle();
// We now check to make sure the TCPClientSocket was not added back to
// the pool.
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
trans.reset();
base::RunLoop().RunUntilIdle();
// Make sure that the socket didn't get recycled after calling the destructor.
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
}
// Make sure that we recycle a socket after reading all of the response body.
TEST_F(HttpNetworkTransactionTest, RecycleSocket) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockRead data_reads[] = {
// A part of the response body is received with the response headers.
MockRead("HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nhel"),
// The rest of the response body is received in two parts.
MockRead("lo"),
MockRead(" world"),
MockRead("junk"), // Should not be read!!
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
std::string status_line = response->headers->GetStatusLine();
EXPECT_EQ("HTTP/1.1 200 OK", status_line);
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello world", response_data);
// Empty the current queue. This is necessary because idle sockets are
// added to the connection pool asynchronously with a PostTask.
base::RunLoop().RunUntilIdle();
// We now check to make sure the socket was added back to the pool.
EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
}
// Make sure that we recycle a SSL socket after reading all of the response
// body.
TEST_F(HttpNetworkTransactionTest, RecycleSSLSocket) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 11\r\n\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello world", response_data);
// Empty the current queue. This is necessary because idle sockets are
// added to the connection pool asynchronously with a PostTask.
base::RunLoop().RunUntilIdle();
// We now check to make sure the socket was added back to the pool.
EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
}
// Grab a SSL socket, use it, and put it back into the pool. Then, reuse it
// from the pool and make sure that we recover okay.
TEST_F(HttpNetworkTransactionTest, RecycleDeadSSLSocket) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"), MockRead("Content-Length: 11\r\n\r\n"),
MockRead("hello world"), MockRead(ASYNC, ERR_CONNECTION_CLOSED)};
SSLSocketDataProvider ssl(ASYNC, OK);
SSLSocketDataProvider ssl2(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
StaticSocketDataProvider data(data_reads, data_writes);
StaticSocketDataProvider data2(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
std::string response_data;
rv = ReadTransaction(trans.get(), &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello world", response_data);
// Empty the current queue. This is necessary because idle sockets are
// added to the connection pool asynchronously with a PostTask.
base::RunLoop().RunUntilIdle();
// We now check to make sure the socket was added back to the pool.
EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
// Now start the second transaction, which should reuse the previous socket.
trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
rv = ReadTransaction(trans.get(), &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello world", response_data);
// Empty the current queue. This is necessary because idle sockets are
// added to the connection pool asynchronously with a PostTask.
base::RunLoop().RunUntilIdle();
// We now check to make sure the socket was added back to the pool.
EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
}
// Grab a socket, use it, and put it back into the pool. Then, make
// low memory notification and ensure the socket pool is flushed.
TEST_F(HttpNetworkTransactionTest, FlushSocketPoolOnLowMemoryNotifications) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.load_flags = 0;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockRead data_reads[] = {
// A part of the response body is received with the response headers.
MockRead("HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nhel"),
// The rest of the response body is received in two parts.
MockRead("lo"), MockRead(" world"),
MockRead("junk"), // Should not be read!!
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
std::string status_line = response->headers->GetStatusLine();
EXPECT_EQ("HTTP/1.1 200 OK", status_line);
// Make memory critical notification and ensure the transaction still has been
// operating right.
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
base::RunLoop().RunUntilIdle();
// Socket should not be flushed as long as it is not idle.
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello world", response_data);
// Empty the current queue. This is necessary because idle sockets are
// added to the connection pool asynchronously with a PostTask.
base::RunLoop().RunUntilIdle();
// We now check to make sure the socket was added back to the pool.
EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
// Idle sockets should be flushed now.
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
}
// Disable idle socket closing on memory pressure.
// Grab a socket, use it, and put it back into the pool. Then, make
// low memory notification and ensure the socket pool is NOT flushed.
TEST_F(HttpNetworkTransactionTest, NoFlushSocketPoolOnLowMemoryNotifications) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.load_flags = 0;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Disable idle socket closing on memory pressure.
session_deps_.disable_idle_sockets_close_on_memory_pressure = true;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockRead data_reads[] = {
// A part of the response body is received with the response headers.
MockRead("HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nhel"),
// The rest of the response body is received in two parts.
MockRead("lo"), MockRead(" world"),
MockRead("junk"), // Should not be read!!
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
std::string status_line = response->headers->GetStatusLine();
EXPECT_EQ("HTTP/1.1 200 OK", status_line);
// Make memory critical notification and ensure the transaction still has been
// operating right.
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
base::RunLoop().RunUntilIdle();
// Socket should not be flushed as long as it is not idle.
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello world", response_data);
// Empty the current queue. This is necessary because idle sockets are
// added to the connection pool asynchronously with a PostTask.
base::RunLoop().RunUntilIdle();
// We now check to make sure the socket was added back to the pool.
EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
// Idle sockets should NOT be flushed on moderate memory pressure.
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
// Idle sockets should NOT be flushed on critical memory pressure.
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
}
// Grab an SSL socket, use it, and put it back into the pool. Then, make
// low memory notification and ensure the socket pool is flushed.
TEST_F(HttpNetworkTransactionTest, FlushSSLSocketPoolOnLowMemoryNotifications) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.load_flags = 0;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"), MockRead("Content-Length: 11\r\n\r\n"),
MockRead("hello world"), MockRead(ASYNC, ERR_CONNECTION_CLOSED)};
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
// Make memory critical notification and ensure the transaction still has been
// operating right.
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello world", response_data);
// Empty the current queue. This is necessary because idle sockets are
// added to the connection pool asynchronously with a PostTask.
base::RunLoop().RunUntilIdle();
// We now check to make sure the socket was added back to the pool.
EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
// Make memory notification once again and ensure idle socket is closed.
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
}
// Make sure that we recycle a socket after a zero-length response.
// http://crbug.com/9880
TEST_F(HttpNetworkTransactionTest, RecycleSocketAfterZeroContentLength) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL(
"http://www.example.org/csi?v=3&s=web&action=&"
"tran=undefined&ei=mAXcSeegAo-SMurloeUN&"
"e=17259,18167,19592,19773,19981,20133,20173,20233&"
"rt=prt.2642,ol.2649,xjs.2951");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
MockRead data_reads[] = {
MockRead("HTTP/1.1 204 No Content\r\n"
"Content-Length: 0\r\n"
"Content-Type: text/html\r\n\r\n"),
MockRead("junk"), // Should not be read!!
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
// Transaction must be created after the MockReads, so it's destroyed before
// them.
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
std::string status_line = response->headers->GetStatusLine();
EXPECT_EQ("HTTP/1.1 204 No Content", status_line);
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("", response_data);
// Empty the current queue. This is necessary because idle sockets are
// added to the connection pool asynchronously with a PostTask.
base::RunLoop().RunUntilIdle();
// We now check to make sure the socket was added back to the pool.
EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
}
TEST_F(HttpNetworkTransactionTest, ResendRequestOnWriteBodyError) {
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(
std::make_unique<UploadBytesElementReader>("foo", 3));
ElementsUploadDataStream upload_data_stream(std::move(element_readers), 0);
HttpRequestInfo request[2];
// Transaction 1: a GET request that succeeds. The socket is recycled
// after use.
request[0].method = "GET";
request[0].url = GURL("http://www.google.com/");
request[0].load_flags = 0;
request[0].traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Transaction 2: a POST request. Reuses the socket kept alive from
// transaction 1. The first attempts fails when writing the POST data.
// This causes the transaction to retry with a new socket. The second
// attempt succeeds.
request[1].method = "POST";
request[1].url = GURL("http://www.google.com/login.cgi");
request[1].upload_data_stream = &upload_data_stream;
request[1].load_flags = 0;
request[1].traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// The first socket is used for transaction 1 and the first attempt of
// transaction 2.
// The response of transaction 1.
MockRead data_reads1[] = {
MockRead("HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
// The mock write results of transaction 1 and the first attempt of
// transaction 2.
MockWrite data_writes1[] = {
MockWrite(SYNCHRONOUS, 64), // GET
MockWrite(SYNCHRONOUS, 93), // POST
MockWrite(SYNCHRONOUS, ERR_CONNECTION_ABORTED), // POST data
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
// The second socket is used for the second attempt of transaction 2.
// The response of transaction 2.
MockRead data_reads2[] = {
MockRead("HTTP/1.1 200 OK\r\nContent-Length: 7\r\n\r\n"),
MockRead("welcome"),
MockRead(SYNCHRONOUS, OK),
};
// The mock write results of the second attempt of transaction 2.
MockWrite data_writes2[] = {
MockWrite(SYNCHRONOUS, 93), // POST
MockWrite(SYNCHRONOUS, 3), // POST data
};
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
const char* const kExpectedResponseData[] = {
"hello world", "welcome"
};
for (int i = 0; i < 2; ++i) {
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&request[i], callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ(kExpectedResponseData[i], response_data);
}
}
// Test the request-challenge-retry sequence for basic auth when there is
// an identity in the URL. The request should be sent as normal, but when
// it fails the identity from the URL is used to answer the challenge.
TEST_F(HttpNetworkTransactionTest, AuthIdentityInURL) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://foo:b@r@www.example.org/");
request.load_flags = LOAD_NORMAL;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// The password contains an escaped character -- for this test to pass it
// will need to be unescaped by HttpNetworkTransaction.
EXPECT_EQ("b%40r", request.url.password());
MockWrite data_writes1[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Length: 10\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED),
};
// After the challenge above, the transaction will be restarted using the
// identity from the url (foo, b@r) to answer the challenge.
MockWrite data_writes2[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJAcg==\r\n\r\n"),
};
MockRead data_reads2[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(trans.IsReadyToRestartForAuth());
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(), callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_FALSE(trans.IsReadyToRestartForAuth());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
// There is no challenge info, since the identity in URL worked.
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(100, response->headers->GetContentLength());
// Empty the current queue.
base::RunLoop().RunUntilIdle();
}
// Test the request-challenge-retry sequence for basic auth when there is an
// incorrect identity in the URL. The identity from the URL should be used only
// once.
TEST_F(HttpNetworkTransactionTest, WrongAuthIdentityInURL) {
HttpRequestInfo request;
request.method = "GET";
// Note: the URL has a username:password in it. The password "baz" is
// wrong (should be "bar").
request.url = GURL("http://foo:baz@www.example.org/");
request.load_flags = LOAD_NORMAL;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes1[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Length: 10\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED),
};
// After the challenge above, the transaction will be restarted using the
// identity from the url (foo, baz) to answer the challenge.
MockWrite data_writes2[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJheg==\r\n\r\n"),
};
MockRead data_reads2[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Length: 10\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED),
};
// After the challenge above, the transaction will be restarted using the
// identity supplied by the user (foo, bar) to answer the challenge.
MockWrite data_writes3[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
MockRead data_reads3[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
StaticSocketDataProvider data3(data_reads3, data_writes3);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
session_deps_.socket_factory->AddSocketDataProvider(&data3);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(trans.IsReadyToRestartForAuth());
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(), callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_FALSE(trans.IsReadyToRestartForAuth());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge));
TestCompletionCallback callback3;
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBar), callback3.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback3.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_FALSE(trans.IsReadyToRestartForAuth());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
// There is no challenge info, since the identity worked.
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(100, response->headers->GetContentLength());
// Empty the current queue.
base::RunLoop().RunUntilIdle();
}
// Test the request-challenge-retry sequence for basic auth when there is a
// correct identity in the URL, but its use is being suppressed. The identity
// from the URL should never be used.
TEST_F(HttpNetworkTransactionTest, AuthIdentityInURLSuppressed) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://foo:bar@www.example.org/");
request.load_flags = LOAD_DO_NOT_USE_EMBEDDED_IDENTITY;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes1[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Length: 10\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED),
};
// After the challenge above, the transaction will be restarted using the
// identity supplied by the user, not the one in the URL, to answer the
// challenge.
MockWrite data_writes3[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
MockRead data_reads3[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data3(data_reads3, data_writes3);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data3);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_FALSE(trans.IsReadyToRestartForAuth());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge));
TestCompletionCallback callback3;
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBar), callback3.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback3.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_FALSE(trans.IsReadyToRestartForAuth());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
// There is no challenge info, since the identity worked.
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(100, response->headers->GetContentLength());
// Empty the current queue.
base::RunLoop().RunUntilIdle();
}
// Test that previously tried username/passwords for a realm get re-used.
TEST_F(HttpNetworkTransactionTest, BasicAuthCacheAndPreauth) {
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Transaction 1: authenticate (foo, bar) on MyRealm1
{
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/x/y/z");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes1[] = {
MockWrite(
"GET /x/y/z HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Length: 10000\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED),
};
// Resend with authorization (username=foo, password=bar)
MockWrite data_writes2[] = {
MockWrite(
"GET /x/y/z HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
// Sever accepts the authorization.
MockRead data_reads2[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge));
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBar),
callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(100, response->headers->GetContentLength());
}
// ------------------------------------------------------------------------
// Transaction 2: authenticate (foo2, bar2) on MyRealm2
{
HttpRequestInfo request;
request.method = "GET";
// Note that Transaction 1 was at /x/y/z, so this is in the same
// protection space as MyRealm1.
request.url = GURL("http://www.example.org/x/y/a/b");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes1[] = {
MockWrite(
"GET /x/y/a/b HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
// Send preemptive authorization for MyRealm1
"Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
// The server didn't like the preemptive authorization, and
// challenges us for a different realm (MyRealm2).
MockRead data_reads1[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
MockRead("WWW-Authenticate: Basic realm=\"MyRealm2\"\r\n"),
MockRead("Content-Length: 10000\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED),
};
// Resend with authorization for MyRealm2 (username=foo2, password=bar2)
MockWrite data_writes2[] = {
MockWrite(
"GET /x/y/a/b HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vMjpiYXIy\r\n\r\n"),
};
// Sever accepts the authorization.
MockRead data_reads2[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->auth_challenge);
EXPECT_FALSE(response->auth_challenge->is_proxy);
EXPECT_EQ("http://www.example.org",
response->auth_challenge->challenger.Serialize());
EXPECT_EQ("MyRealm2", response->auth_challenge->realm);
EXPECT_EQ(kBasicAuthScheme, response->auth_challenge->scheme);
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(kFoo2, kBar2),
callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(100, response->headers->GetContentLength());
}
// ------------------------------------------------------------------------
// Transaction 3: Resend a request in MyRealm's protection space --
// succeed with preemptive authorization.
{
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/x/y/z2");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes1[] = {
MockWrite(
"GET /x/y/z2 HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
// The authorization for MyRealm1 gets sent preemptively
// (since the url is in the same protection space)
"Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
// Sever accepts the preemptive authorization
MockRead data_reads1[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(100, response->headers->GetContentLength());
}
// ------------------------------------------------------------------------
// Transaction 4: request another URL in MyRealm (however the
// url is not known to belong to the protection space, so no pre-auth).
{
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/x/1");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes1[] = {
MockWrite(
"GET /x/1 HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Length: 10000\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED),
};
// Resend with authorization from MyRealm's cache.
MockWrite data_writes2[] = {
MockWrite(
"GET /x/1 HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
// Sever accepts the authorization.
MockRead data_reads2[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(trans.IsReadyToRestartForAuth());
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(), callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_FALSE(trans.IsReadyToRestartForAuth());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(100, response->headers->GetContentLength());
}
// ------------------------------------------------------------------------
// Transaction 5: request a URL in MyRealm, but the server rejects the
// cached identity. Should invalidate and re-prompt.
{
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/p/q/t");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes1[] = {
MockWrite(
"GET /p/q/t HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Length: 10000\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED),
};
// Resend with authorization from cache for MyRealm.
MockWrite data_writes2[] = {
MockWrite(
"GET /p/q/t HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
// Sever rejects the authorization.
MockRead data_reads2[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Length: 10000\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED),
};
// At this point we should prompt for new credentials for MyRealm.
// Restart with username=foo3, password=foo4.
MockWrite data_writes3[] = {
MockWrite(
"GET /p/q/t HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vMzpiYXIz\r\n\r\n"),
};
// Sever accepts the authorization.
MockRead data_reads3[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
StaticSocketDataProvider data3(data_reads3, data_writes3);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
session_deps_.socket_factory->AddSocketDataProvider(&data3);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(trans.IsReadyToRestartForAuth());
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(), callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_FALSE(trans.IsReadyToRestartForAuth());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge));
TestCompletionCallback callback3;
rv = trans.RestartWithAuth(AuthCredentials(kFoo3, kBar3),
callback3.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback3.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(100, response->headers->GetContentLength());
}
}
// Tests that nonce count increments when multiple auth attempts
// are started with the same nonce.
TEST_F(HttpNetworkTransactionTest, DigestPreAuthNonceCount) {
HttpAuthHandlerDigest::Factory* digest_factory =
new HttpAuthHandlerDigest::Factory();
HttpAuthHandlerDigest::FixedNonceGenerator* nonce_generator =
new HttpAuthHandlerDigest::FixedNonceGenerator("0123456789abcdef");
digest_factory->set_nonce_generator(nonce_generator);
session_deps_.http_auth_handler_factory.reset(digest_factory);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Transaction 1: authenticate (foo, bar) on MyRealm1
{
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/x/y/z");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes1[] = {
MockWrite(
"GET /x/y/z HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
MockRead("WWW-Authenticate: Digest realm=\"digestive\", nonce=\"OU812\", "
"algorithm=MD5, qop=\"auth\"\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
// Resend with authorization (username=foo, password=bar)
MockWrite data_writes2[] = {
MockWrite(
"GET /x/y/z HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Digest username=\"foo\", realm=\"digestive\", "
"nonce=\"OU812\", uri=\"/x/y/z\", algorithm=MD5, "
"response=\"03ffbcd30add722589c1de345d7a927f\", qop=auth, "
"nc=00000001, cnonce=\"0123456789abcdef\"\r\n\r\n"),
};
// Sever accepts the authorization.
MockRead data_reads2[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckDigestServerAuth(response->auth_challenge));
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBar),
callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
}
// ------------------------------------------------------------------------
// Transaction 2: Request another resource in digestive's protection space.
// This will preemptively add an Authorization header which should have an
// "nc" value of 2 (as compared to 1 in the first use.
{
HttpRequestInfo request;
request.method = "GET";
// Note that Transaction 1 was at /x/y/z, so this is in the same
// protection space as digest.
request.url = GURL("http://www.example.org/x/y/a/b");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes1[] = {
MockWrite(
"GET /x/y/a/b HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Digest username=\"foo\", realm=\"digestive\", "
"nonce=\"OU812\", uri=\"/x/y/a/b\", algorithm=MD5, "
"response=\"d6f9a2c07d1c5df7b89379dca1269b35\", qop=auth, "
"nc=00000002, cnonce=\"0123456789abcdef\"\r\n\r\n"),
};
// Sever accepts the authorization.
MockRead data_reads1[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
}
}
// Test the ResetStateForRestart() private method.
TEST_F(HttpNetworkTransactionTest, ResetStateForRestart) {
// Create a transaction (the dependencies aren't important).
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Setup some state (which we expect ResetStateForRestart() will clear).
trans.read_buf_ = base::MakeRefCounted<IOBuffer>(15);
trans.read_buf_len_ = 15;
trans.request_headers_.SetHeader("Authorization", "NTLM");
// Setup state in response_
HttpResponseInfo* response = &trans.response_;
response->auth_challenge = base::nullopt;
response->ssl_info.cert_status = static_cast<CertStatus>(-1); // Nonsensical.
response->response_time = base::Time::Now();
response->was_cached = true; // (Wouldn't ever actually be true...)
{ // Setup state for response_.vary_data
HttpRequestInfo request;
std::string temp("HTTP/1.1 200 OK\nVary: foo, bar\n\n");
std::replace(temp.begin(), temp.end(), '\n', '\0');
scoped_refptr<HttpResponseHeaders> headers(new HttpResponseHeaders(temp));
request.extra_headers.SetHeader("Foo", "1");
request.extra_headers.SetHeader("bar", "23");
EXPECT_TRUE(response->vary_data.Init(request, *headers.get()));
}
// Cause the above state to be reset.
trans.ResetStateForRestart();
// Verify that the state that needed to be reset, has been reset.
EXPECT_FALSE(trans.read_buf_);
EXPECT_EQ(0, trans.read_buf_len_);
EXPECT_TRUE(trans.request_headers_.IsEmpty());
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_FALSE(response->headers);
EXPECT_FALSE(response->was_cached);
EXPECT_EQ(0U, response->ssl_info.cert_status);
EXPECT_FALSE(response->vary_data.is_valid());
}
// Test HTTPS connections to a site with a bad certificate
TEST_F(HttpNetworkTransactionTest, HTTPSBadCertificate) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider ssl_bad_certificate;
StaticSocketDataProvider data(data_reads, data_writes);
SSLSocketDataProvider ssl_bad(ASYNC, ERR_CERT_AUTHORITY_INVALID);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSocketDataProvider(&ssl_bad_certificate);
session_deps_.socket_factory->AddSocketDataProvider(&data);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_bad);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_CERT_AUTHORITY_INVALID));
rv = trans.RestartIgnoringLastError(callback.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_EQ(100, response->headers->GetContentLength());
}
// Test HTTPS connections to a site with a bad certificate, going through a
// proxy
TEST_F(HttpNetworkTransactionTest, HTTPSBadCertificateViaProxy) {
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite proxy_writes[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
MockRead proxy_reads[] = {
MockRead("HTTP/1.0 200 Connected\r\n\r\n"),
MockRead(SYNCHRONOUS, OK)
};
MockWrite data_writes[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 Connected\r\n\r\n"),
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider ssl_bad_certificate(proxy_reads, proxy_writes);
StaticSocketDataProvider data(data_reads, data_writes);
SSLSocketDataProvider ssl_bad(ASYNC, ERR_CERT_AUTHORITY_INVALID);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSocketDataProvider(&ssl_bad_certificate);
session_deps_.socket_factory->AddSocketDataProvider(&data);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_bad);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback;
for (int i = 0; i < 2; i++) {
session_deps_.socket_factory->ResetNextMockIndexes();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_CERT_AUTHORITY_INVALID));
rv = trans.RestartIgnoringLastError(callback.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_EQ(100, response->headers->GetContentLength());
}
}
// Test HTTPS connections to a site, going through an HTTPS proxy
TEST_F(HttpNetworkTransactionTest, HTTPSViaHttpsProxy) {
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"HTTPS proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog net_log;
session_deps_.net_log = &net_log;
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 Connected\r\n\r\n"),
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
SSLSocketDataProvider tunnel_ssl(ASYNC, OK); // SSL through the tunnel
session_deps_.socket_factory->AddSocketDataProvider(&data);
session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
session_deps_.socket_factory->AddSSLSocketDataProvider(&tunnel_ssl);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->proxy_server.is_https());
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(100, response->headers->GetContentLength());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReusedWithPac(load_timing_info,
CONNECT_TIMING_HAS_SSL_TIMES);
}
// Test that an HTTPS Proxy cannot redirect a CONNECT request for main frames.
TEST_F(HttpNetworkTransactionTest, RedirectOfHttpsConnectViaHttpsProxy) {
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"HTTPS proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog net_log;
session_deps_.net_log = &net_log;
const base::TimeDelta kTimeIncrement = base::TimeDelta::FromSeconds(4);
session_deps_.host_resolver->set_ondemand_mode(true);
HttpRequestInfo request;
request.load_flags = LOAD_MAIN_FRAME_DEPRECATED;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite(ASYNC, 0,
"CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
// Pause on first read.
MockRead(ASYNC, ERR_IO_PENDING, 1),
MockRead(ASYNC, 2, "HTTP/1.1 302 Redirect\r\n"),
MockRead(ASYNC, 3, "Location: http://login.example.com/\r\n"),
MockRead(ASYNC, 4, "Content-Length: 0\r\n\r\n"),
};
SequencedSocketData data(MockConnect(ASYNC, OK), data_reads, data_writes);
SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
session_deps_.socket_factory->AddSocketDataProvider(&data);
session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_TRUE(session_deps_.host_resolver->has_pending_requests());
// Host resolution takes |kTimeIncrement|.
FastForwardBy(kTimeIncrement);
// Resolving the current request with |ResolveNow| will cause the pending
// request to instantly complete, and the async connect will start as well.
session_deps_.host_resolver->ResolveOnlyRequestNow();
// Connecting takes |kTimeIncrement|.
FastForwardBy(kTimeIncrement);
data.RunUntilPaused();
// The server takes |kTimeIncrement| to respond.
FastForwardBy(kTimeIncrement);
data.Resume();
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_TUNNEL_CONNECTION_FAILED));
}
// Test that an HTTPS Proxy cannot redirect a CONNECT request for subresources.
TEST_F(HttpNetworkTransactionTest,
RedirectOfHttpsConnectSubresourceViaHttpsProxy) {
base::HistogramTester histograms;
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"HTTPS proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog net_log;
session_deps_.net_log = &net_log;
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite(ASYNC, 0,
"CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead(ASYNC, 1, "HTTP/1.1 302 Redirect\r\n"),
MockRead(ASYNC, 2, "Location: http://login.example.com/\r\n"),
MockRead(ASYNC, 3, "Content-Length: 0\r\n\r\n"),
};
SequencedSocketData data(MockConnect(ASYNC, OK), data_reads, data_writes);
SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
session_deps_.socket_factory->AddSocketDataProvider(&data);
session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_TUNNEL_CONNECTION_FAILED));
}
// Test that an HTTPS Proxy which was auto-detected cannot redirect a CONNECT
// request for main frames.
TEST_F(HttpNetworkTransactionTest,
RedirectOfHttpsConnectViaAutoDetectedHttpsProxy) {
base::HistogramTester histograms;
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromAutoDetectedPacResult(
"HTTPS proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog net_log;
session_deps_.net_log = &net_log;
HttpRequestInfo request;
request.load_flags = LOAD_MAIN_FRAME_DEPRECATED;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite(ASYNC, 0,
"CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead(ASYNC, 1, "HTTP/1.1 302 Redirect\r\n"),
MockRead(ASYNC, 2, "Location: http://login.example.com/\r\n"),
MockRead(ASYNC, 3, "Content-Length: 0\r\n\r\n"),
};
SequencedSocketData data(MockConnect(ASYNC, OK), data_reads, data_writes);
SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
session_deps_.socket_factory->AddSocketDataProvider(&data);
session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_TUNNEL_CONNECTION_FAILED));
}
// Tests that an HTTPS (SPDY) Proxy's cannot redirect a CONNECT request for main
// frames.
TEST_F(HttpNetworkTransactionTest, RedirectOfHttpsConnectViaSpdyProxy) {
base::HistogramTester histograms;
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog net_log;
session_deps_.net_log = &net_log;
const base::TimeDelta kTimeIncrement = base::TimeDelta::FromSeconds(4);
session_deps_.host_resolver->set_ondemand_mode(true);
HttpRequestInfo request;
request.method = "GET";
request.load_flags = LOAD_MAIN_FRAME_DEPRECATED;
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
spdy::SpdySerializedFrame conn(spdy_util_.ConstructSpdyConnect(
nullptr, 0, 1, HttpProxyConnectJob::kH2QuicTunnelPriority,
HostPortPair("www.example.org", 443)));
spdy::SpdySerializedFrame goaway(
spdy_util_.ConstructSpdyRstStream(1, spdy::ERROR_CODE_CANCEL));
MockWrite data_writes[] = {
CreateMockWrite(conn, 0, SYNCHRONOUS),
CreateMockWrite(goaway, 3, SYNCHRONOUS),
};
static const char* const kExtraHeaders[] = {
"location",
"http://login.example.com/",
};
spdy::SpdySerializedFrame resp(spdy_util_.ConstructSpdyReplyError(
"302", kExtraHeaders, base::size(kExtraHeaders) / 2, 1));
MockRead data_reads[] = {
// Pause on first read.
MockRead(ASYNC, ERR_IO_PENDING, 1), CreateMockRead(resp, 2),
MockRead(ASYNC, 0, 4), // EOF
};
SequencedSocketData data(MockConnect(ASYNC, OK), data_reads, data_writes);
SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
proxy_ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSocketDataProvider(&data);
session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_TRUE(session_deps_.host_resolver->has_pending_requests());
// Host resolution takes |kTimeIncrement|.
FastForwardBy(kTimeIncrement);
// Resolving the current request with |ResolveNow| will cause the pending
// request to instantly complete, and the async connect will start as well.
session_deps_.host_resolver->ResolveOnlyRequestNow();
// Connecting takes |kTimeIncrement|.
FastForwardBy(kTimeIncrement);
data.RunUntilPaused();
FastForwardBy(kTimeIncrement);
data.Resume();
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_TUNNEL_CONNECTION_FAILED));
}
// Test that an HTTPS proxy's response to a CONNECT request is filtered.
TEST_F(HttpNetworkTransactionTest, ErrorResponseToHttpsConnectViaHttpsProxy) {
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead("HTTP/1.1 404 Not Found\r\n"),
MockRead("Content-Length: 23\r\n\r\n"),
MockRead("The host does not exist"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
session_deps_.socket_factory->AddSocketDataProvider(&data);
session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_TUNNEL_CONNECTION_FAILED));
// TODO(juliatuttle): Anything else to check here?
}
// Test that a SPDY proxy's response to a CONNECT request is filtered.
TEST_F(HttpNetworkTransactionTest, ErrorResponseToHttpsConnectViaSpdyProxy) {
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
spdy::SpdySerializedFrame conn(spdy_util_.ConstructSpdyConnect(
nullptr, 0, 1, HttpProxyConnectJob::kH2QuicTunnelPriority,
HostPortPair("www.example.org", 443)));
spdy::SpdySerializedFrame rst(
spdy_util_.ConstructSpdyRstStream(1, spdy::ERROR_CODE_CANCEL));
MockWrite data_writes[] = {
CreateMockWrite(conn, 0), CreateMockWrite(rst, 3),
};
static const char* const kExtraHeaders[] = {
"location",
"http://login.example.com/",
};
spdy::SpdySerializedFrame resp(spdy_util_.ConstructSpdyReplyError(
"404", kExtraHeaders, base::size(kExtraHeaders) / 2, 1));
spdy::SpdySerializedFrame body(
spdy_util_.ConstructSpdyDataFrame(1, "The host does not exist", true));
MockRead data_reads[] = {
CreateMockRead(resp, 1), CreateMockRead(body, 2),
MockRead(ASYNC, 0, 4), // EOF
};
SequencedSocketData data(data_reads, data_writes);
SSLSocketDataProvider proxy_ssl(ASYNC, OK); // SSL to the proxy
proxy_ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSocketDataProvider(&data);
session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy_ssl);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_TUNNEL_CONNECTION_FAILED));
// TODO(juliatuttle): Anything else to check here?
}
// Test the request-challenge-retry sequence for basic auth, through
// a SPDY proxy over a single SPDY session.
TEST_F(HttpNetworkTransactionTest, BasicAuthSpdyProxy) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
// when the no authentication data flag is set.
request.load_flags = LOAD_DO_NOT_SEND_AUTH_DATA;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against https proxy server "myproxy:70".
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"HTTPS myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Since we have proxy, should try to establish tunnel.
spdy::SpdySerializedFrame req(spdy_util_.ConstructSpdyConnect(
nullptr, 0, 1, HttpProxyConnectJob::kH2QuicTunnelPriority,
HostPortPair("www.example.org", 443)));
spdy::SpdySerializedFrame rst(
spdy_util_.ConstructSpdyRstStream(1, spdy::ERROR_CODE_CANCEL));
spdy_util_.UpdateWithStreamDestruction(1);
// After calling trans.RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
const char* const kAuthCredentials[] = {
"proxy-authorization", "Basic Zm9vOmJhcg==",
};
spdy::SpdySerializedFrame connect2(spdy_util_.ConstructSpdyConnect(
kAuthCredentials, base::size(kAuthCredentials) / 2, 3,
HttpProxyConnectJob::kH2QuicTunnelPriority,
HostPortPair("www.example.org", 443)));
// fetch https://www.example.org/ via HTTP
const char get[] =
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n";
spdy::SpdySerializedFrame wrapped_get(
spdy_util_.ConstructSpdyDataFrame(3, get, false));
MockWrite spdy_writes[] = {
CreateMockWrite(req, 0, ASYNC), CreateMockWrite(rst, 2, ASYNC),
CreateMockWrite(connect2, 3), CreateMockWrite(wrapped_get, 5),
};
// The proxy responds to the connect with a 407, using a persistent
// connection.
const char kAuthStatus[] = "407";
const char* const kAuthChallenge[] = {
"proxy-authenticate", "Basic realm=\"MyRealm1\"",
};
spdy::SpdySerializedFrame conn_auth_resp(spdy_util_.ConstructSpdyReplyError(
kAuthStatus, kAuthChallenge, base::size(kAuthChallenge) / 2, 1));
spdy::SpdySerializedFrame conn_resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 3));
const char resp[] = "HTTP/1.1 200 OK\r\n"
"Content-Length: 5\r\n\r\n";
spdy::SpdySerializedFrame wrapped_get_resp(
spdy_util_.ConstructSpdyDataFrame(3, resp, false));
spdy::SpdySerializedFrame wrapped_body(
spdy_util_.ConstructSpdyDataFrame(3, "hello", false));
MockRead spdy_reads[] = {
CreateMockRead(conn_auth_resp, 1, ASYNC),
CreateMockRead(conn_resp, 4, ASYNC),
CreateMockRead(wrapped_get_resp, 6, ASYNC),
CreateMockRead(wrapped_body, 7, ASYNC),
MockRead(ASYNC, OK, 8), // EOF. May or may not be read.
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
// Negotiate SPDY to the proxy
SSLSocketDataProvider proxy(ASYNC, OK);
proxy.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy);
// Vanilla SSL to the server
SSLSocketDataProvider server(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&server);
TestCompletionCallback callback1;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
TestNetLogEntry::List entries;
log.GetEntries(&entries);
size_t pos = ExpectLogContainsSomewhere(
entries, 0, NetLogEventType::HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
NetLogEventPhase::NONE);
ExpectLogContainsSomewhere(
entries, pos,
NetLogEventType::HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
NetLogEventPhase::NONE);
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(407, response->headers->response_code());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
EXPECT_TRUE(response->auth_challenge.has_value());
EXPECT_TRUE(CheckBasicSecureProxyAuth(response->auth_challenge));
TestCompletionCallback callback2;
rv = trans->RestartWithAuth(AuthCredentials(kFoo, kBar),
callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans->GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(5, response->headers->GetContentLength());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
// The password prompt info should not be set.
EXPECT_FALSE(response->auth_challenge.has_value());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReusedWithPac(load_timing_info,
CONNECT_TIMING_HAS_SSL_TIMES);
trans.reset();
session->CloseAllConnections();
}
// Test that an explicitly trusted SPDY proxy can push a resource from an
// origin that is different from that of its associated resource.
TEST_F(HttpNetworkTransactionTest, CrossOriginSPDYProxyPush) {
// Configure the proxy delegate to allow cross-origin SPDY pushes.
auto proxy_delegate = std::make_unique<TestProxyDelegate>();
proxy_delegate->set_trusted_spdy_proxy(net::ProxyServer::FromURI(
"https://myproxy:443", net::ProxyServer::SCHEME_HTTP));
HttpRequestInfo request;
HttpRequestInfo push_request;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
request.method = "GET";
request.url = GURL("http://www.example.org/");
push_request.method = "GET";
push_request.url = GURL("http://www.another-origin.com/foo.dat");
push_request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against https proxy server "myproxy:443".
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"HTTPS myproxy:443", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
session_deps_.proxy_resolution_service->SetProxyDelegate(
proxy_delegate.get());
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
spdy::SpdySerializedFrame stream1_syn(
spdy_util_.ConstructSpdyGet("http://www.example.org/", 1, LOWEST));
spdy::SpdySerializedFrame stream2_priority(
spdy_util_.ConstructSpdyPriority(2, 1, IDLE, true));
MockWrite spdy_writes[] = {
CreateMockWrite(stream1_syn, 0, ASYNC),
CreateMockWrite(stream2_priority, 3, ASYNC),
};
spdy::SpdySerializedFrame stream2_syn(spdy_util_.ConstructSpdyPush(
nullptr, 0, 2, 1, "http://www.another-origin.com/foo.dat"));
spdy::SpdySerializedFrame stream1_reply(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame stream1_body(
spdy_util_.ConstructSpdyDataFrame(1, true));
spdy::SpdySerializedFrame stream2_body(
spdy_util_.ConstructSpdyDataFrame(2, "pushed", true));
MockRead spdy_reads[] = {
CreateMockRead(stream2_syn, 1, ASYNC),
CreateMockRead(stream1_reply, 2, ASYNC),
CreateMockRead(stream1_body, 4, ASYNC),
CreateMockRead(stream2_body, 5, ASYNC),
MockRead(SYNCHRONOUS, ERR_IO_PENDING, 6), // Force a hang
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
// Negotiate SPDY to the proxy
SSLSocketDataProvider proxy(ASYNC, OK);
proxy.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy);
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
auto push_trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
rv = push_trans->Start(&push_request, callback.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* push_response = push_trans->GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(200, response->headers->response_code());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
std::string response_data;
rv = ReadTransaction(trans.get(), &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello!", response_data);
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReusedWithPac(load_timing_info,
CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
// Verify the pushed stream.
EXPECT_TRUE(push_response->headers);
EXPECT_EQ(200, push_response->headers->response_code());
rv = ReadTransaction(push_trans.get(), &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("pushed", response_data);
LoadTimingInfo push_load_timing_info;
EXPECT_TRUE(push_trans->GetLoadTimingInfo(&push_load_timing_info));
TestLoadTimingReusedWithPac(push_load_timing_info);
// The transactions should share a socket ID, despite being for different
// origins.
EXPECT_EQ(load_timing_info.socket_log_id,
push_load_timing_info.socket_log_id);
trans.reset();
push_trans.reset();
session->CloseAllConnections();
}
// Test that an explicitly trusted SPDY proxy cannot push HTTPS content.
TEST_F(HttpNetworkTransactionTest, CrossOriginProxyPushCorrectness) {
// Configure the proxy delegate to allow cross-origin SPDY pushes.
auto proxy_delegate = std::make_unique<TestProxyDelegate>();
proxy_delegate->set_trusted_spdy_proxy(net::ProxyServer::FromURI(
"https://myproxy:443", net::ProxyServer::SCHEME_HTTP));
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://myproxy:443", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
// Enable cross-origin push.
session_deps_.proxy_resolution_service->SetProxyDelegate(
proxy_delegate.get());
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
spdy::SpdySerializedFrame stream1_syn(
spdy_util_.ConstructSpdyGet("http://www.example.org/", 1, LOWEST));
spdy::SpdySerializedFrame push_rst(
spdy_util_.ConstructSpdyRstStream(2, spdy::ERROR_CODE_REFUSED_STREAM));
MockWrite spdy_writes[] = {
CreateMockWrite(stream1_syn, 0, ASYNC), CreateMockWrite(push_rst, 3),
};
spdy::SpdySerializedFrame stream1_reply(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame stream1_body(
spdy_util_.ConstructSpdyDataFrame(1, true));
spdy::SpdySerializedFrame stream2_syn(spdy_util_.ConstructSpdyPush(
nullptr, 0, 2, 1, "https://www.another-origin.com/foo.dat"));
MockRead spdy_reads[] = {
CreateMockRead(stream1_reply, 1, ASYNC),
CreateMockRead(stream2_syn, 2, ASYNC),
CreateMockRead(stream1_body, 4, ASYNC),
MockRead(SYNCHRONOUS, ERR_IO_PENDING, 5), // Force a hang
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
// Negotiate SPDY to the proxy
SSLSocketDataProvider proxy(ASYNC, OK);
proxy.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy);
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(200, response->headers->response_code());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
std::string response_data;
rv = ReadTransaction(trans.get(), &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello!", response_data);
trans.reset();
session->CloseAllConnections();
}
// Test that an explicitly trusted SPDY proxy can push same-origin HTTPS
// resources.
TEST_F(HttpNetworkTransactionTest, SameOriginProxyPushCorrectness) {
// Configure the proxy delegate to allow cross-origin SPDY pushes.
auto proxy_delegate = std::make_unique<TestProxyDelegate>();
proxy_delegate->set_trusted_spdy_proxy(
net::ProxyServer::FromURI("myproxy:70", net::ProxyServer::SCHEME_HTTP));
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against https proxy server "myproxy:70".
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
// Enable cross-origin push.
session_deps_.proxy_resolution_service->SetProxyDelegate(
proxy_delegate.get());
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
spdy::SpdySerializedFrame stream1_syn(
spdy_util_.ConstructSpdyGet("http://www.example.org/", 1, LOWEST));
spdy::SpdySerializedFrame stream2_priority(
spdy_util_.ConstructSpdyPriority(2, 1, IDLE, true));
MockWrite spdy_writes[] = {
CreateMockWrite(stream1_syn, 0, ASYNC),
CreateMockWrite(stream2_priority, 3, ASYNC),
};
spdy::SpdySerializedFrame stream1_reply(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame stream2_syn(spdy_util_.ConstructSpdyPush(
nullptr, 0, 2, 1, "http://www.example.org/foo.dat"));
spdy::SpdySerializedFrame stream1_body(
spdy_util_.ConstructSpdyDataFrame(1, true));
spdy::SpdySerializedFrame stream2_reply(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame stream2_body(
spdy_util_.ConstructSpdyDataFrame(1, true));
MockRead spdy_reads[] = {
CreateMockRead(stream1_reply, 1, ASYNC),
CreateMockRead(stream2_syn, 2, ASYNC),
CreateMockRead(stream1_body, 4, ASYNC),
CreateMockRead(stream2_body, 5, ASYNC),
MockRead(SYNCHRONOUS, ERR_IO_PENDING, 6), // Force a hang
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
// Negotiate SPDY to the proxy
SSLSocketDataProvider proxy(ASYNC, OK);
proxy.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&proxy);
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(200, response->headers->response_code());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
std::string response_data;
rv = ReadTransaction(trans.get(), &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello!", response_data);
trans.reset();
session->CloseAllConnections();
}
// Test HTTPS connections to a site with a bad certificate, going through an
// HTTPS proxy
TEST_F(HttpNetworkTransactionTest, HTTPSBadCertificateViaHttpsProxy) {
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Attempt to fetch the URL from a server with a bad cert
MockWrite bad_cert_writes[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
MockRead bad_cert_reads[] = {
MockRead("HTTP/1.0 200 Connected\r\n\r\n"),
MockRead(SYNCHRONOUS, OK)
};
// Attempt to fetch the URL with a good cert
MockWrite good_data_writes[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead good_cert_reads[] = {
MockRead("HTTP/1.0 200 Connected\r\n\r\n"),
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider ssl_bad_certificate(bad_cert_reads, bad_cert_writes);
StaticSocketDataProvider data(good_cert_reads, good_data_writes);
SSLSocketDataProvider ssl_bad(ASYNC, ERR_CERT_AUTHORITY_INVALID);
SSLSocketDataProvider ssl(ASYNC, OK);
// SSL to the proxy, then CONNECT request, then SSL with bad certificate
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
session_deps_.socket_factory->AddSocketDataProvider(&ssl_bad_certificate);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_bad);
// SSL to the proxy, then CONNECT request, then valid SSL certificate
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
session_deps_.socket_factory->AddSocketDataProvider(&data);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_CERT_AUTHORITY_INVALID));
rv = trans.RestartIgnoringLastError(callback.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_EQ(100, response->headers->GetContentLength());
}
TEST_F(HttpNetworkTransactionTest, BuildRequest_UserAgent) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.extra_headers.SetHeader(HttpRequestHeaders::kUserAgent,
"Chromium Ultra Awesome X Edition");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"User-Agent: Chromium Ultra Awesome X Edition\r\n\r\n"),
};
// Lastly, the server responds with the actual content.
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
}
TEST_F(HttpNetworkTransactionTest, BuildRequest_UserAgentOverTunnel) {
// Test user agent values, used both for the request header of the original
// request, and the value returned by the HttpUserAgentSettings. nullptr means
// no request header / no HttpUserAgentSettings object.
const char* kTestUserAgents[] = {nullptr, "", "Foopy"};
for (const char* setting_user_agent : kTestUserAgents) {
if (!setting_user_agent) {
session_deps_.http_user_agent_settings.reset();
} else {
session_deps_.http_user_agent_settings =
std::make_unique<StaticHttpUserAgentSettings>(
std::string() /* accept-language */, setting_user_agent);
}
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixed("myproxy:70",
TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
for (const char* request_user_agent : kTestUserAgents) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
if (request_user_agent) {
request.extra_headers.SetHeader(HttpRequestHeaders::kUserAgent,
request_user_agent);
}
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
std::string expected_request;
if (!setting_user_agent || strlen(setting_user_agent) == 0) {
expected_request =
"CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n";
} else {
expected_request = base::StringPrintf(
"CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"User-Agent: %s\r\n\r\n",
setting_user_agent);
}
MockWrite data_writes[] = {
MockWrite(expected_request.c_str()),
};
MockRead data_reads[] = {
// Return an error, so the transaction stops here (this test isn't
// interested in the rest).
MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Proxy-Connection: close\r\n\r\n"),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
}
}
}
TEST_F(HttpNetworkTransactionTest, BuildRequest_Referer) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.extra_headers.SetHeader(HttpRequestHeaders::kReferer,
"http://the.previous.site.com/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Referer: http://the.previous.site.com/\r\n\r\n"),
};
// Lastly, the server responds with the actual content.
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
}
TEST_F(HttpNetworkTransactionTest, BuildRequest_PostContentLengthZero) {
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite(
"POST / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 0\r\n\r\n"),
};
// Lastly, the server responds with the actual content.
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
}
TEST_F(HttpNetworkTransactionTest, BuildRequest_PutContentLengthZero) {
HttpRequestInfo request;
request.method = "PUT";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite(
"PUT / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 0\r\n\r\n"),
};
// Lastly, the server responds with the actual content.
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
}
TEST_F(HttpNetworkTransactionTest, BuildRequest_HeadContentLengthZero) {
HttpRequestInfo request;
request.method = "HEAD";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite("HEAD / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
// Lastly, the server responds with the actual content.
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
}
TEST_F(HttpNetworkTransactionTest, BuildRequest_CacheControlNoCache) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.load_flags = LOAD_BYPASS_CACHE;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Pragma: no-cache\r\n"
"Cache-Control: no-cache\r\n\r\n"),
};
// Lastly, the server responds with the actual content.
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
}
TEST_F(HttpNetworkTransactionTest, BuildRequest_CacheControlValidateCache) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.load_flags = LOAD_VALIDATE_CACHE;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Cache-Control: max-age=0\r\n\r\n"),
};
// Lastly, the server responds with the actual content.
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
}
TEST_F(HttpNetworkTransactionTest, BuildRequest_ExtraHeaders) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.extra_headers.SetHeader("FooHeader", "Bar");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"FooHeader: Bar\r\n\r\n"),
};
// Lastly, the server responds with the actual content.
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
}
TEST_F(HttpNetworkTransactionTest, BuildRequest_ExtraHeadersStripped) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.extra_headers.SetHeader("referer", "www.foo.com");
request.extra_headers.SetHeader("hEllo", "Kitty");
request.extra_headers.SetHeader("FoO", "bar");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"referer: www.foo.com\r\n"
"hEllo: Kitty\r\n"
"FoO: bar\r\n\r\n"),
};
// Lastly, the server responds with the actual content.
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
}
TEST_F(HttpNetworkTransactionTest, SOCKS4_HTTP_GET) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"SOCKS myproxy:1080", TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog net_log;
session_deps_.net_log = &net_log;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
char write_buffer[] = { 0x04, 0x01, 0x00, 0x50, 127, 0, 0, 1, 0 };
char read_buffer[] = { 0x00, 0x5A, 0x00, 0x00, 0, 0, 0, 0 };
MockWrite data_writes[] = {
MockWrite(ASYNC, write_buffer, base::size(write_buffer)),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n")};
MockRead data_reads[] = {
MockRead(ASYNC, read_buffer, base::size(read_buffer)),
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
MockRead("Payload"), MockRead(SYNCHRONOUS, OK)};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_EQ(ProxyServer::SCHEME_SOCKS4, response->proxy_server.scheme());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReusedWithPac(load_timing_info,
CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
std::string response_text;
rv = ReadTransaction(&trans, &response_text);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("Payload", response_text);
}
TEST_F(HttpNetworkTransactionTest, SOCKS4_SSL_GET) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"SOCKS myproxy:1080", TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog net_log;
session_deps_.net_log = &net_log;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
unsigned char write_buffer[] = { 0x04, 0x01, 0x01, 0xBB, 127, 0, 0, 1, 0 };
unsigned char read_buffer[] = { 0x00, 0x5A, 0x00, 0x00, 0, 0, 0, 0 };
MockWrite data_writes[] = {
MockWrite(ASYNC, reinterpret_cast<char*>(write_buffer),
base::size(write_buffer)),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n")};
MockRead data_reads[] = {
MockRead(ASYNC, reinterpret_cast<char*>(read_buffer),
base::size(read_buffer)),
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
MockRead("Payload"), MockRead(SYNCHRONOUS, OK)};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReusedWithPac(load_timing_info,
CONNECT_TIMING_HAS_SSL_TIMES);
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_EQ(ProxyServer::SCHEME_SOCKS4, response->proxy_server.scheme());
std::string response_text;
rv = ReadTransaction(&trans, &response_text);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("Payload", response_text);
}
TEST_F(HttpNetworkTransactionTest, SOCKS4_HTTP_GET_no_PAC) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"socks4://myproxy:1080", TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog net_log;
session_deps_.net_log = &net_log;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
char write_buffer[] = { 0x04, 0x01, 0x00, 0x50, 127, 0, 0, 1, 0 };
char read_buffer[] = { 0x00, 0x5A, 0x00, 0x00, 0, 0, 0, 0 };
MockWrite data_writes[] = {
MockWrite(ASYNC, write_buffer, base::size(write_buffer)),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n")};
MockRead data_reads[] = {
MockRead(ASYNC, read_buffer, base::size(read_buffer)),
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
MockRead("Payload"), MockRead(SYNCHRONOUS, OK)};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReused(load_timing_info,
CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
std::string response_text;
rv = ReadTransaction(&trans, &response_text);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("Payload", response_text);
}
TEST_F(HttpNetworkTransactionTest, SOCKS5_HTTP_GET) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"SOCKS5 myproxy:1080", TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog net_log;
session_deps_.net_log = &net_log;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
const char kSOCKS5OkRequest[] = {
0x05, // Version
0x01, // Command (CONNECT)
0x00, // Reserved.
0x03, // Address type (DOMAINNAME).
0x0F, // Length of domain (15)
'w', 'w', 'w', '.', 'e', 'x', 'a', 'm', 'p', 'l', 'e', // Domain string
'.', 'o', 'r', 'g', 0x00, 0x50, // 16-bit port (80)
};
const char kSOCKS5OkResponse[] =
{ 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
MockWrite data_writes[] = {
MockWrite(ASYNC, kSOCKS5GreetRequest, base::size(kSOCKS5GreetRequest)),
MockWrite(ASYNC, kSOCKS5OkRequest, base::size(kSOCKS5OkRequest)),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n")};
MockRead data_reads[] = {
MockRead(ASYNC, kSOCKS5GreetResponse, base::size(kSOCKS5GreetResponse)),
MockRead(ASYNC, kSOCKS5OkResponse, base::size(kSOCKS5OkResponse)),
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
MockRead("Payload"),
MockRead(SYNCHRONOUS, OK)};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_EQ(ProxyServer::SCHEME_SOCKS5, response->proxy_server.scheme());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReusedWithPac(load_timing_info,
CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
std::string response_text;
rv = ReadTransaction(&trans, &response_text);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("Payload", response_text);
}
TEST_F(HttpNetworkTransactionTest, SOCKS5_SSL_GET) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"SOCKS5 myproxy:1080", TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog net_log;
session_deps_.net_log = &net_log;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
const unsigned char kSOCKS5OkRequest[] = {
0x05, // Version
0x01, // Command (CONNECT)
0x00, // Reserved.
0x03, // Address type (DOMAINNAME).
0x0F, // Length of domain (15)
'w', 'w', 'w', '.', 'e', 'x', 'a', 'm', 'p', 'l', 'e', // Domain string
'.', 'o', 'r', 'g', 0x01, 0xBB, // 16-bit port (443)
};
const char kSOCKS5OkResponse[] =
{ 0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0x00, 0x00 };
MockWrite data_writes[] = {
MockWrite(ASYNC, kSOCKS5GreetRequest, base::size(kSOCKS5GreetRequest)),
MockWrite(ASYNC, reinterpret_cast<const char*>(kSOCKS5OkRequest),
base::size(kSOCKS5OkRequest)),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n")};
MockRead data_reads[] = {
MockRead(ASYNC, kSOCKS5GreetResponse, base::size(kSOCKS5GreetResponse)),
MockRead(ASYNC, kSOCKS5OkResponse, base::size(kSOCKS5OkResponse)),
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
MockRead("Payload"),
MockRead(SYNCHRONOUS, OK)};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_EQ(ProxyServer::SCHEME_SOCKS5, response->proxy_server.scheme());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReusedWithPac(load_timing_info,
CONNECT_TIMING_HAS_SSL_TIMES);
std::string response_text;
rv = ReadTransaction(&trans, &response_text);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("Payload", response_text);
}
namespace {
// Tests that for connection endpoints the group ids are correctly set.
struct GroupIdTest {
std::string proxy_server;
std::string url;
ClientSocketPool::GroupId expected_group_id;
bool ssl;
};
std::unique_ptr<HttpNetworkSession> SetupSessionForGroupIdTests(
SpdySessionDependencies* session_deps_) {
std::unique_ptr<HttpNetworkSession> session(CreateSession(session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
AlternativeService alternative_service(kProtoHTTP2, "", 444);
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
http_server_properties->SetHttp2AlternativeService(
url::SchemeHostPort("https", "host.with.alternate", 443),
alternative_service, expiration);
return session;
}
int GroupIdTransactionHelper(const std::string& url,
HttpNetworkSession* session) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL(url);
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session);
TestCompletionCallback callback;
// We do not complete this request, the dtor will clean the transaction up.
return trans.Start(&request, callback.callback(), NetLogWithSource());
}
} // namespace
TEST_F(HttpNetworkTransactionTest, GroupIdForDirectConnections) {
const GroupIdTest tests[] = {
{
"", // unused
"http://www.example.org/direct",
ClientSocketPool::GroupId(HostPortPair("www.example.org", 80),
ClientSocketPool::SocketType::kHttp,
PrivacyMode::PRIVACY_MODE_DISABLED),
false,
},
{
"", // unused
"http://[2001:1418:13:1::25]/direct",
ClientSocketPool::GroupId(HostPortPair("2001:1418:13:1::25", 80),
ClientSocketPool::SocketType::kHttp,
PrivacyMode::PRIVACY_MODE_DISABLED),
false,
},
// SSL Tests
{
"", // unused
"https://www.example.org/direct_ssl",
ClientSocketPool::GroupId(HostPortPair("www.example.org", 443),
ClientSocketPool::SocketType::kSsl,
PrivacyMode::PRIVACY_MODE_DISABLED),
true,
},
{
"", // unused
"https://[2001:1418:13:1::25]/direct",
ClientSocketPool::GroupId(HostPortPair("2001:1418:13:1::25", 443),
ClientSocketPool::SocketType::kSsl,
PrivacyMode::PRIVACY_MODE_DISABLED),
true,
},
{
"", // unused
"https://host.with.alternate/direct",
ClientSocketPool::GroupId(HostPortPair("host.with.alternate", 443),
ClientSocketPool::SocketType::kSsl,
PrivacyMode::PRIVACY_MODE_DISABLED),
true,
},
};
for (size_t i = 0; i < base::size(tests); ++i) {
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixed(tests[i].proxy_server,
TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(
SetupSessionForGroupIdTests(&session_deps_));
HttpNetworkSessionPeer peer(session.get());
CaptureGroupIdTransportSocketPool* transport_conn_pool =
new CaptureGroupIdTransportSocketPool(&dummy_connect_job_params_);
auto mock_pool_manager = std::make_unique<MockClientSocketPoolManager>();
mock_pool_manager->SetSocketPool(ProxyServer::Direct(),
base::WrapUnique(transport_conn_pool));
peer.SetClientSocketPoolManager(std::move(mock_pool_manager));
EXPECT_EQ(ERR_IO_PENDING,
GroupIdTransactionHelper(tests[i].url, session.get()));
EXPECT_EQ(tests[i].expected_group_id,
transport_conn_pool->last_group_id_received());
EXPECT_TRUE(transport_conn_pool->socket_requested());
}
}
TEST_F(HttpNetworkTransactionTest, GroupIdForHTTPProxyConnections) {
const GroupIdTest tests[] = {
{
"http_proxy",
"http://www.example.org/http_proxy_normal",
ClientSocketPool::GroupId(HostPortPair("www.example.org", 80),
ClientSocketPool::SocketType::kHttp,
PrivacyMode::PRIVACY_MODE_DISABLED),
false,
},
// SSL Tests
{
"http_proxy",
"https://www.example.org/http_connect_ssl",
ClientSocketPool::GroupId(HostPortPair("www.example.org", 443),
ClientSocketPool::SocketType::kSsl,
PrivacyMode::PRIVACY_MODE_DISABLED),
true,
},
{
"http_proxy",
"https://host.with.alternate/direct",
ClientSocketPool::GroupId(HostPortPair("host.with.alternate", 443),
ClientSocketPool::SocketType::kSsl,
PrivacyMode::PRIVACY_MODE_DISABLED),
true,
},
{
"http_proxy",
"ftp://ftp.google.com/http_proxy_normal",
ClientSocketPool::GroupId(HostPortPair("ftp.google.com", 21),
ClientSocketPool::SocketType::kFtp,
PrivacyMode::PRIVACY_MODE_DISABLED),
false,
},
};
for (size_t i = 0; i < base::size(tests); ++i) {
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixed(tests[i].proxy_server,
TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(
SetupSessionForGroupIdTests(&session_deps_));
HttpNetworkSessionPeer peer(session.get());
ProxyServer proxy_server(ProxyServer::SCHEME_HTTP,
HostPortPair("http_proxy", 80));
CaptureGroupIdTransportSocketPool* http_proxy_pool =
new CaptureGroupIdTransportSocketPool(&dummy_connect_job_params_);
auto mock_pool_manager = std::make_unique<MockClientSocketPoolManager>();
mock_pool_manager->SetSocketPool(proxy_server,
base::WrapUnique(http_proxy_pool));
peer.SetClientSocketPoolManager(std::move(mock_pool_manager));
EXPECT_EQ(ERR_IO_PENDING,
GroupIdTransactionHelper(tests[i].url, session.get()));
EXPECT_EQ(tests[i].expected_group_id,
http_proxy_pool->last_group_id_received());
}
}
TEST_F(HttpNetworkTransactionTest, GroupIdForSOCKSConnections) {
const GroupIdTest tests[] = {
{
"socks4://socks_proxy:1080",
"http://www.example.org/socks4_direct",
ClientSocketPool::GroupId(HostPortPair("www.example.org", 80),
ClientSocketPool::SocketType::kHttp,
PrivacyMode::PRIVACY_MODE_DISABLED),
false,
},
{
"socks5://socks_proxy:1080",
"http://www.example.org/socks5_direct",
ClientSocketPool::GroupId(HostPortPair("www.example.org", 80),
ClientSocketPool::SocketType::kHttp,
PrivacyMode::PRIVACY_MODE_DISABLED),
false,
},
// SSL Tests
{
"socks4://socks_proxy:1080",
"https://www.example.org/socks4_ssl",
ClientSocketPool::GroupId(HostPortPair("www.example.org", 443),
ClientSocketPool::SocketType::kSsl,
PrivacyMode::PRIVACY_MODE_DISABLED),
true,
},
{
"socks5://socks_proxy:1080",
"https://www.example.org/socks5_ssl",
ClientSocketPool::GroupId(HostPortPair("www.example.org", 443),
ClientSocketPool::SocketType::kSsl,
PrivacyMode::PRIVACY_MODE_DISABLED),
true,
},
{
"socks4://socks_proxy:1080",
"https://host.with.alternate/direct",
ClientSocketPool::GroupId(HostPortPair("host.with.alternate", 443),
ClientSocketPool::SocketType::kSsl,
PrivacyMode::PRIVACY_MODE_DISABLED),
true,
},
};
for (size_t i = 0; i < base::size(tests); ++i) {
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixed(tests[i].proxy_server,
TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(
SetupSessionForGroupIdTests(&session_deps_));
HttpNetworkSessionPeer peer(session.get());
ProxyServer proxy_server(
ProxyServer::FromURI(tests[i].proxy_server, ProxyServer::SCHEME_HTTP));
ASSERT_TRUE(proxy_server.is_valid());
CaptureGroupIdTransportSocketPool* socks_conn_pool =
new CaptureGroupIdTransportSocketPool(&dummy_connect_job_params_);
auto mock_pool_manager = std::make_unique<MockClientSocketPoolManager>();
mock_pool_manager->SetSocketPool(proxy_server,
base::WrapUnique(socks_conn_pool));
peer.SetClientSocketPoolManager(std::move(mock_pool_manager));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
EXPECT_EQ(ERR_IO_PENDING,
GroupIdTransactionHelper(tests[i].url, session.get()));
EXPECT_EQ(tests[i].expected_group_id,
socks_conn_pool->last_group_id_received());
}
}
TEST_F(HttpNetworkTransactionTest, ReconsiderProxyAfterFailedConnection) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"myproxy:70;foobar:80", TRAFFIC_ANNOTATION_FOR_TESTS);
// This simulates failure resolving all hostnames; that means we will fail
// connecting to both proxies (myproxy:70 and foobar:80).
session_deps_.host_resolver->rules()->AddSimulatedFailure("*");
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_PROXY_CONNECTION_FAILED));
}
// Make sure we can handle an error when writing the request.
TEST_F(HttpNetworkTransactionTest, RequestWriteError) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.foo.com/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite write_failure[] = {
MockWrite(ASYNC, ERR_CONNECTION_RESET),
};
StaticSocketDataProvider data(base::span<MockRead>(), write_failure);
session_deps_.socket_factory->AddSocketDataProvider(&data);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
TestCompletionCallback callback;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
IPEndPoint endpoint;
EXPECT_TRUE(trans.GetRemoteEndpoint(&endpoint));
EXPECT_LT(0u, endpoint.address().size());
}
// Check that a connection closed after the start of the headers finishes ok.
TEST_F(HttpNetworkTransactionTest, ConnectionClosedAfterStartOfHeaders) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.foo.com/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockRead data_reads[] = {
MockRead("HTTP/1."),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
TestCompletionCallback callback;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.0 200 OK", response->headers->GetStatusLine());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("", response_data);
IPEndPoint endpoint;
EXPECT_TRUE(trans.GetRemoteEndpoint(&endpoint));
EXPECT_LT(0u, endpoint.address().size());
}
// Make sure that a dropped connection while draining the body for auth
// restart does the right thing.
TEST_F(HttpNetworkTransactionTest, DrainResetOK) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes1[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 401 Unauthorized\r\n"),
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 14\r\n\r\n"),
MockRead("Unauth"),
MockRead(ASYNC, ERR_CONNECTION_RESET),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
// After calling trans.RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite data_writes2[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
};
// Lastly, the server responds with the actual content.
MockRead data_reads2[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(CheckBasicServerAuth(response->auth_challenge));
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBar), callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(100, response->headers->GetContentLength());
}
// Test HTTPS connections going through a proxy that sends extra data.
TEST_F(HttpNetworkTransactionTest, HTTPSViaProxyWithExtraData) {
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockRead proxy_reads[] = {
MockRead("HTTP/1.0 200 Connected\r\n\r\nExtra data"),
MockRead(SYNCHRONOUS, OK)
};
StaticSocketDataProvider data(proxy_reads, base::span<MockWrite>());
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSocketDataProvider(&data);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback;
session_deps_.socket_factory->ResetNextMockIndexes();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_TUNNEL_CONNECTION_FAILED));
}
TEST_F(HttpNetworkTransactionTest, LargeContentLengthThenClose) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\nContent-Length:6719476739\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.0 200 OK", response->headers->GetStatusLine());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsError(ERR_CONTENT_LENGTH_MISMATCH));
}
TEST_F(HttpNetworkTransactionTest, UploadFileSmallerThanLength) {
base::FilePath temp_file_path;
ASSERT_TRUE(base::CreateTemporaryFile(&temp_file_path));
const uint64_t kFakeSize = 100000; // file is actually blank
UploadFileElementReader::ScopedOverridingContentLengthForTests
overriding_content_length(kFakeSize);
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(std::make_unique<UploadFileElementReader>(
base::ThreadTaskRunnerHandle::Get().get(), temp_file_path, 0,
std::numeric_limits<uint64_t>::max(), base::Time()));
ElementsUploadDataStream upload_data_stream(std::move(element_readers), 0);
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.example.org/upload");
request.upload_data_stream = &upload_data_stream;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_UPLOAD_FILE_CHANGED));
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->headers);
base::DeleteFile(temp_file_path, false);
}
TEST_F(HttpNetworkTransactionTest, UploadUnreadableFile) {
base::FilePath temp_file;
ASSERT_TRUE(base::CreateTemporaryFile(&temp_file));
std::string temp_file_content("Unreadable file.");
ASSERT_EQ(static_cast<int>(temp_file_content.length()),
base::WriteFile(temp_file, temp_file_content.c_str(),
temp_file_content.length()));
ASSERT_TRUE(base::MakeFileUnreadable(temp_file));
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(std::make_unique<UploadFileElementReader>(
base::ThreadTaskRunnerHandle::Get().get(), temp_file, 0,
std::numeric_limits<uint64_t>::max(), base::Time()));
ElementsUploadDataStream upload_data_stream(std::move(element_readers), 0);
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.example.org/upload");
request.upload_data_stream = &upload_data_stream;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// If we try to upload an unreadable file, the transaction should fail.
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
StaticSocketDataProvider data;
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_ACCESS_DENIED));
base::DeleteFile(temp_file, false);
}
TEST_F(HttpNetworkTransactionTest, CancelDuringInitRequestBody) {
class FakeUploadElementReader : public UploadElementReader {
public:
FakeUploadElementReader() = default;
~FakeUploadElementReader() override = default;
CompletionOnceCallback TakeCallback() { return std::move(callback_); }
// UploadElementReader overrides:
int Init(CompletionOnceCallback callback) override {
callback_ = std::move(callback);
return ERR_IO_PENDING;
}
uint64_t GetContentLength() const override { return 0; }
uint64_t BytesRemaining() const override { return 0; }
int Read(IOBuffer* buf,
int buf_length,
CompletionOnceCallback callback) override {
return ERR_FAILED;
}
private:
CompletionOnceCallback callback_;
};
FakeUploadElementReader* fake_reader = new FakeUploadElementReader;
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(base::WrapUnique(fake_reader));
ElementsUploadDataStream upload_data_stream(std::move(element_readers), 0);
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.example.org/upload");
request.upload_data_stream = &upload_data_stream;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
StaticSocketDataProvider data;
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
base::RunLoop().RunUntilIdle();
// Transaction is pending on request body initialization.
CompletionOnceCallback init_callback = fake_reader->TakeCallback();
ASSERT_FALSE(init_callback.is_null());
// Return Init()'s result after the transaction gets destroyed.
trans.reset();
std::move(init_callback).Run(OK); // Should not crash.
}
// Tests that changes to Auth realms are treated like auth rejections.
TEST_F(HttpNetworkTransactionTest, ChangeAuthRealms) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// First transaction will request a resource and receive a Basic challenge
// with realm="first_realm".
MockWrite data_writes1[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 401 Unauthorized\r\n"
"WWW-Authenticate: Basic realm=\"first_realm\"\r\n"
"\r\n"),
};
// After calling trans.RestartWithAuth(), provide an Authentication header
// for first_realm. The server will reject and provide a challenge with
// second_realm.
MockWrite data_writes2[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zmlyc3Q6YmF6\r\n"
"\r\n"),
};
MockRead data_reads2[] = {
MockRead("HTTP/1.1 401 Unauthorized\r\n"
"WWW-Authenticate: Basic realm=\"second_realm\"\r\n"
"\r\n"),
};
// This again fails, and goes back to first_realm. Make sure that the
// entry is removed from cache.
MockWrite data_writes3[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic c2Vjb25kOmZvdQ==\r\n"
"\r\n"),
};
MockRead data_reads3[] = {
MockRead("HTTP/1.1 401 Unauthorized\r\n"
"WWW-Authenticate: Basic realm=\"first_realm\"\r\n"
"\r\n"),
};
// Try one last time (with the correct password) and get the resource.
MockWrite data_writes4[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zmlyc3Q6YmFy\r\n"
"\r\n"),
};
MockRead data_reads4[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=iso-8859-1\r\n"
"Content-Length: 5\r\n"
"\r\n"
"hello"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
StaticSocketDataProvider data3(data_reads3, data_writes3);
StaticSocketDataProvider data4(data_reads4, data_writes4);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
session_deps_.socket_factory->AddSocketDataProvider(&data3);
session_deps_.socket_factory->AddSocketDataProvider(&data4);
TestCompletionCallback callback1;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Issue the first request with Authorize headers. There should be a
// password prompt for first_realm waiting to be filled in after the
// transaction completes.
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
base::Optional<AuthChallengeInfo> challenge = response->auth_challenge;
ASSERT_TRUE(challenge);
EXPECT_FALSE(challenge->is_proxy);
EXPECT_EQ("http://www.example.org", challenge->challenger.Serialize());
EXPECT_EQ("first_realm", challenge->realm);
EXPECT_EQ(kBasicAuthScheme, challenge->scheme);
// Issue the second request with an incorrect password. There should be a
// password prompt for second_realm waiting to be filled in after the
// transaction completes.
TestCompletionCallback callback2;
rv = trans.RestartWithAuth(AuthCredentials(kFirst, kBaz),
callback2.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback2.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
challenge = response->auth_challenge;
ASSERT_TRUE(challenge);
EXPECT_FALSE(challenge->is_proxy);
EXPECT_EQ("http://www.example.org", challenge->challenger.Serialize());
EXPECT_EQ("second_realm", challenge->realm);
EXPECT_EQ(kBasicAuthScheme, challenge->scheme);
// Issue the third request with another incorrect password. There should be
// a password prompt for first_realm waiting to be filled in. If the password
// prompt is not present, it indicates that the HttpAuthCacheEntry for
// first_realm was not correctly removed.
TestCompletionCallback callback3;
rv = trans.RestartWithAuth(AuthCredentials(kSecond, kFou),
callback3.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback3.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
challenge = response->auth_challenge;
ASSERT_TRUE(challenge);
EXPECT_FALSE(challenge->is_proxy);
EXPECT_EQ("http://www.example.org", challenge->challenger.Serialize());
EXPECT_EQ("first_realm", challenge->realm);
EXPECT_EQ(kBasicAuthScheme, challenge->scheme);
// Issue the fourth request with the correct password and username.
TestCompletionCallback callback4;
rv = trans.RestartWithAuth(AuthCredentials(kFirst, kBar),
callback4.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback4.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
}
// Regression test for https://crbug.com/754395.
TEST_F(HttpNetworkTransactionTest, IgnoreAltSvcWithInvalidCert) {
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead(kAlternativeServiceHttpHeader),
MockRead("\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "wildcard.pem");
ASSERT_TRUE(ssl.ssl_info.cert);
ssl.ssl_info.cert_status = CERT_STATUS_COMMON_NAME_INVALID;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
url::SchemeHostPort test_server(request.url);
HttpServerProperties* http_server_properties =
session->http_server_properties();
EXPECT_TRUE(
http_server_properties->GetAlternativeServiceInfos(test_server).empty());
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
EXPECT_FALSE(response->was_fetched_via_spdy);
EXPECT_FALSE(response->was_alpn_negotiated);
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
EXPECT_TRUE(
http_server_properties->GetAlternativeServiceInfos(test_server).empty());
}
TEST_F(HttpNetworkTransactionTest, HonorAlternativeServiceHeader) {
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead(kAlternativeServiceHttpHeader),
MockRead("\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "wildcard.pem");
ASSERT_TRUE(ssl.ssl_info.cert);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
url::SchemeHostPort test_server(request.url);
HttpServerProperties* http_server_properties =
session->http_server_properties();
EXPECT_TRUE(
http_server_properties->GetAlternativeServiceInfos(test_server).empty());
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
EXPECT_FALSE(response->was_fetched_via_spdy);
EXPECT_FALSE(response->was_alpn_negotiated);
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
AlternativeServiceInfoVector alternative_service_info_vector =
http_server_properties->GetAlternativeServiceInfos(test_server);
ASSERT_EQ(1u, alternative_service_info_vector.size());
AlternativeService alternative_service(kProtoHTTP2, "mail.example.org", 443);
EXPECT_EQ(alternative_service,
alternative_service_info_vector[0].alternative_service());
}
// Regression test for https://crbug.com/615497.
TEST_F(HttpNetworkTransactionTest,
DoNotParseAlternativeServiceHeaderOnInsecureRequest) {
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead(kAlternativeServiceHttpHeader),
MockRead("\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.load_flags = 0;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
url::SchemeHostPort test_server(request.url);
HttpServerProperties* http_server_properties =
session->http_server_properties();
EXPECT_TRUE(
http_server_properties->GetAlternativeServiceInfos(test_server).empty());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
EXPECT_FALSE(response->was_fetched_via_spdy);
EXPECT_FALSE(response->was_alpn_negotiated);
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
EXPECT_TRUE(
http_server_properties->GetAlternativeServiceInfos(test_server).empty());
}
// HTTP/2 Alternative Services should be disabled by default.
// TODO(bnc): Remove when https://crbug.com/615413 is fixed.
TEST_F(HttpNetworkTransactionTest,
DisableHTTP2AlternativeServicesWithDifferentHost) {
session_deps_.enable_http2_alternative_service = false;
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.load_flags = 0;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
StaticSocketDataProvider first_data;
first_data.set_connect_data(mock_connect);
session_deps_.socket_factory->AddSocketDataProvider(&first_data);
SSLSocketDataProvider ssl_http11(ASYNC, OK);
ssl_http11.next_proto = kProtoHTTP11;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_http11);
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n\r\n"), MockRead("hello world"),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider second_data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&second_data);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
AlternativeService alternative_service(kProtoHTTP2, "different.example.org",
444);
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
http_server_properties->SetHttp2AlternativeService(
url::SchemeHostPort(request.url), alternative_service, expiration);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
// Alternative service is not used, request fails.
EXPECT_THAT(callback.GetResult(rv), IsError(ERR_CONNECTION_REFUSED));
}
// Regression test for https://crbug.com/615497:
// Alternative Services should be disabled for http origin.
TEST_F(HttpNetworkTransactionTest,
DisableAlternativeServicesForInsecureOrigin) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.load_flags = 0;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
StaticSocketDataProvider first_data;
first_data.set_connect_data(mock_connect);
session_deps_.socket_factory->AddSocketDataProvider(&first_data);
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n\r\n"), MockRead("hello world"),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider second_data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&second_data);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
AlternativeService alternative_service(kProtoHTTP2, "", 444);
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
http_server_properties->SetHttp2AlternativeService(
url::SchemeHostPort(request.url), alternative_service, expiration);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
// Alternative service is not used, request fails.
EXPECT_THAT(callback.GetResult(rv), IsError(ERR_CONNECTION_REFUSED));
}
TEST_F(HttpNetworkTransactionTest, ClearAlternativeServices) {
// Set an alternative service for origin.
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
url::SchemeHostPort test_server("https", "www.example.org", 443);
AlternativeService alternative_service(kProtoQUIC, "", 80);
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
http_server_properties->SetQuicAlternativeService(
test_server, alternative_service, expiration,
session->params().quic_supported_versions);
EXPECT_EQ(
1u,
http_server_properties->GetAlternativeServiceInfos(test_server).size());
// Send a clear header.
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Alt-Svc: clear\r\n"),
MockRead("\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "wildcard.pem");
ASSERT_TRUE(ssl.ssl_info.cert);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestCompletionCallback callback;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
EXPECT_FALSE(response->was_fetched_via_spdy);
EXPECT_FALSE(response->was_alpn_negotiated);
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
EXPECT_TRUE(
http_server_properties->GetAlternativeServiceInfos(test_server).empty());
}
TEST_F(HttpNetworkTransactionTest, HonorMultipleAlternativeServiceHeaders) {
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Alt-Svc: h2=\"www.example.com:443\","),
MockRead("h2=\":1234\"\r\n\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "wildcard.pem");
ASSERT_TRUE(ssl.ssl_info.cert);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
url::SchemeHostPort test_server("https", "www.example.org", 443);
HttpServerProperties* http_server_properties =
session->http_server_properties();
EXPECT_TRUE(
http_server_properties->GetAlternativeServiceInfos(test_server).empty());
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
EXPECT_FALSE(response->was_fetched_via_spdy);
EXPECT_FALSE(response->was_alpn_negotiated);
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
AlternativeServiceInfoVector alternative_service_info_vector =
http_server_properties->GetAlternativeServiceInfos(test_server);
ASSERT_EQ(2u, alternative_service_info_vector.size());
AlternativeService alternative_service(kProtoHTTP2, "www.example.com", 443);
EXPECT_EQ(alternative_service,
alternative_service_info_vector[0].alternative_service());
AlternativeService alternative_service_2(kProtoHTTP2, "www.example.org",
1234);
EXPECT_EQ(alternative_service_2,
alternative_service_info_vector[1].alternative_service());
}
TEST_F(HttpNetworkTransactionTest, IdentifyQuicBroken) {
url::SchemeHostPort server("https", "origin.example.org", 443);
HostPortPair alternative("alternative.example.org", 443);
std::string origin_url = "https://origin.example.org:443";
std::string alternative_url = "https://alternative.example.org:443";
// Negotiate HTTP/1.1 with alternative.example.org.
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP11;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
// HTTP/1.1 data for request.
MockWrite http_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: alternative.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead http_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=iso-8859-1\r\n"
"Content-Length: 40\r\n\r\n"
"first HTTP/1.1 response from alternative"),
};
StaticSocketDataProvider http_data(http_reads, http_writes);
session_deps_.socket_factory->AddSocketDataProvider(&http_data);
StaticSocketDataProvider data_refused;
data_refused.set_connect_data(MockConnect(ASYNC, ERR_CONNECTION_REFUSED));
session_deps_.socket_factory->AddSocketDataProvider(&data_refused);
// Set up a QUIC alternative service for server.
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
AlternativeService alternative_service(kProtoQUIC, alternative);
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
http_server_properties->SetQuicAlternativeService(
server, alternative_service, expiration,
HttpNetworkSession::Params().quic_supported_versions);
// Mark the QUIC alternative service as broken.
http_server_properties->MarkAlternativeServiceBroken(alternative_service);
HttpRequestInfo request;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
request.method = "GET";
request.url = GURL(origin_url);
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestCompletionCallback callback;
NetErrorDetails details;
EXPECT_FALSE(details.quic_broken);
trans.Start(&request, callback.callback(), NetLogWithSource());
trans.PopulateNetErrorDetails(&details);
EXPECT_TRUE(details.quic_broken);
}
TEST_F(HttpNetworkTransactionTest, IdentifyQuicNotBroken) {
url::SchemeHostPort server("https", "origin.example.org", 443);
HostPortPair alternative1("alternative1.example.org", 443);
HostPortPair alternative2("alternative2.example.org", 443);
std::string origin_url = "https://origin.example.org:443";
std::string alternative_url1 = "https://alternative1.example.org:443";
std::string alternative_url2 = "https://alternative2.example.org:443";
// Negotiate HTTP/1.1 with alternative1.example.org.
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP11;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
// HTTP/1.1 data for request.
MockWrite http_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: alternative1.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead http_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=iso-8859-1\r\n"
"Content-Length: 40\r\n\r\n"
"first HTTP/1.1 response from alternative1"),
};
StaticSocketDataProvider http_data(http_reads, http_writes);
session_deps_.socket_factory->AddSocketDataProvider(&http_data);
StaticSocketDataProvider data_refused;
data_refused.set_connect_data(MockConnect(ASYNC, ERR_CONNECTION_REFUSED));
session_deps_.socket_factory->AddSocketDataProvider(&data_refused);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
// Set up two QUIC alternative services for server.
AlternativeServiceInfoVector alternative_service_info_vector;
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
AlternativeService alternative_service1(kProtoQUIC, alternative1);
alternative_service_info_vector.push_back(
AlternativeServiceInfo::CreateQuicAlternativeServiceInfo(
alternative_service1, expiration,
session->params().quic_supported_versions));
AlternativeService alternative_service2(kProtoQUIC, alternative2);
alternative_service_info_vector.push_back(
AlternativeServiceInfo::CreateQuicAlternativeServiceInfo(
alternative_service2, expiration,
session->params().quic_supported_versions));
http_server_properties->SetAlternativeServices(
server, alternative_service_info_vector);
// Mark one of the QUIC alternative service as broken.
http_server_properties->MarkAlternativeServiceBroken(alternative_service1);
EXPECT_EQ(2u,
http_server_properties->GetAlternativeServiceInfos(server).size());
HttpRequestInfo request;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
request.method = "GET";
request.url = GURL(origin_url);
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestCompletionCallback callback;
NetErrorDetails details;
EXPECT_FALSE(details.quic_broken);
trans.Start(&request, callback.callback(), NetLogWithSource());
trans.PopulateNetErrorDetails(&details);
EXPECT_FALSE(details.quic_broken);
}
TEST_F(HttpNetworkTransactionTest, MarkBrokenAlternateProtocolAndFallback) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
StaticSocketDataProvider first_data;
first_data.set_connect_data(mock_connect);
session_deps_.socket_factory->AddSocketDataProvider(&first_data);
SSLSocketDataProvider ssl_http11(ASYNC, OK);
ssl_http11.next_proto = kProtoHTTP11;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_http11);
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n\r\n"),
MockRead("hello world"),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider second_data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&second_data);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
const url::SchemeHostPort server(request.url);
// Port must be < 1024, or the header will be ignored (since initial port was
// port 80 (another restricted port).
// Port is ignored by MockConnect anyway.
const AlternativeService alternative_service(kProtoHTTP2, "www.example.org",
666);
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
http_server_properties->SetHttp2AlternativeService(
server, alternative_service, expiration);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
const AlternativeServiceInfoVector alternative_service_info_vector =
http_server_properties->GetAlternativeServiceInfos(server);
ASSERT_EQ(1u, alternative_service_info_vector.size());
EXPECT_EQ(alternative_service,
alternative_service_info_vector[0].alternative_service());
EXPECT_TRUE(
http_server_properties->IsAlternativeServiceBroken(alternative_service));
}
// Ensure that we are not allowed to redirect traffic via an alternate protocol
// to an unrestricted (port >= 1024) when the original traffic was on a
// restricted port (port < 1024). Ensure that we can redirect in all other
// cases.
TEST_F(HttpNetworkTransactionTest, AlternateProtocolPortRestrictedBlocked) {
HttpRequestInfo restricted_port_request;
restricted_port_request.method = "GET";
restricted_port_request.url = GURL("https://www.example.org:1023/");
restricted_port_request.load_flags = 0;
restricted_port_request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
StaticSocketDataProvider first_data;
first_data.set_connect_data(mock_connect);
session_deps_.socket_factory->AddSocketDataProvider(&first_data);
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n\r\n"),
MockRead("hello world"),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider second_data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&second_data);
SSLSocketDataProvider ssl_http11(ASYNC, OK);
ssl_http11.next_proto = kProtoHTTP11;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_http11);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
const int kUnrestrictedAlternatePort = 1024;
AlternativeService alternative_service(kProtoHTTP2, "www.example.org",
kUnrestrictedAlternatePort);
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
http_server_properties->SetHttp2AlternativeService(
url::SchemeHostPort(restricted_port_request.url), alternative_service,
expiration);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&restricted_port_request, callback.callback(),
NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// Invalid change to unrestricted port should fail.
EXPECT_THAT(callback.WaitForResult(), IsError(ERR_CONNECTION_REFUSED));
}
// Ensure that we are allowed to redirect traffic via an alternate protocol to
// an unrestricted (port >= 1024) when the original traffic was on a restricted
// port (port < 1024) if we set |enable_user_alternate_protocol_ports|.
TEST_F(HttpNetworkTransactionTest, AlternateProtocolPortRestrictedPermitted) {
session_deps_.enable_user_alternate_protocol_ports = true;
HttpRequestInfo restricted_port_request;
restricted_port_request.method = "GET";
restricted_port_request.url = GURL("https://www.example.org:1023/");
restricted_port_request.load_flags = 0;
restricted_port_request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
StaticSocketDataProvider first_data;
first_data.set_connect_data(mock_connect);
session_deps_.socket_factory->AddSocketDataProvider(&first_data);
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n\r\n"),
MockRead("hello world"),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider second_data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&second_data);
SSLSocketDataProvider ssl_http11(ASYNC, OK);
ssl_http11.next_proto = kProtoHTTP11;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_http11);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
const int kUnrestrictedAlternatePort = 1024;
AlternativeService alternative_service(kProtoHTTP2, "www.example.org",
kUnrestrictedAlternatePort);
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
http_server_properties->SetHttp2AlternativeService(
url::SchemeHostPort(restricted_port_request.url), alternative_service,
expiration);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
EXPECT_EQ(ERR_IO_PENDING,
trans.Start(&restricted_port_request, callback.callback(),
NetLogWithSource()));
// Change to unrestricted port should succeed.
EXPECT_THAT(callback.WaitForResult(), IsOk());
}
// Ensure that we are not allowed to redirect traffic via an alternate protocol
// to an unrestricted (port >= 1024) when the original traffic was on a
// restricted port (port < 1024). Ensure that we can redirect in all other
// cases.
TEST_F(HttpNetworkTransactionTest, AlternateProtocolPortRestrictedAllowed) {
HttpRequestInfo restricted_port_request;
restricted_port_request.method = "GET";
restricted_port_request.url = GURL("https://www.example.org:1023/");
restricted_port_request.load_flags = 0;
restricted_port_request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
StaticSocketDataProvider first_data;
first_data.set_connect_data(mock_connect);
session_deps_.socket_factory->AddSocketDataProvider(&first_data);
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n\r\n"),
MockRead("hello world"),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider second_data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&second_data);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
const int kRestrictedAlternatePort = 80;
AlternativeService alternative_service(kProtoHTTP2, "www.example.org",
kRestrictedAlternatePort);
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
http_server_properties->SetHttp2AlternativeService(
url::SchemeHostPort(restricted_port_request.url), alternative_service,
expiration);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&restricted_port_request, callback.callback(),
NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// Valid change to restricted port should pass.
EXPECT_THAT(callback.WaitForResult(), IsOk());
}
// Ensure that we are not allowed to redirect traffic via an alternate protocol
// to an unrestricted (port >= 1024) when the original traffic was on a
// restricted port (port < 1024). Ensure that we can redirect in all other
// cases.
TEST_F(HttpNetworkTransactionTest, AlternateProtocolPortUnrestrictedAllowed1) {
HttpRequestInfo unrestricted_port_request;
unrestricted_port_request.method = "GET";
unrestricted_port_request.url = GURL("https://www.example.org:1024/");
unrestricted_port_request.load_flags = 0;
unrestricted_port_request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
StaticSocketDataProvider first_data;
first_data.set_connect_data(mock_connect);
session_deps_.socket_factory->AddSocketDataProvider(&first_data);
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n\r\n"),
MockRead("hello world"),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider second_data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&second_data);
SSLSocketDataProvider ssl_http11(ASYNC, OK);
ssl_http11.next_proto = kProtoHTTP11;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_http11);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
const int kRestrictedAlternatePort = 80;
AlternativeService alternative_service(kProtoHTTP2, "www.example.org",
kRestrictedAlternatePort);
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
http_server_properties->SetHttp2AlternativeService(
url::SchemeHostPort(unrestricted_port_request.url), alternative_service,
expiration);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&unrestricted_port_request, callback.callback(),
NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// Valid change to restricted port should pass.
EXPECT_THAT(callback.WaitForResult(), IsOk());
}
// Ensure that we are not allowed to redirect traffic via an alternate protocol
// to an unrestricted (port >= 1024) when the original traffic was on a
// restricted port (port < 1024). Ensure that we can redirect in all other
// cases.
TEST_F(HttpNetworkTransactionTest, AlternateProtocolPortUnrestrictedAllowed2) {
HttpRequestInfo unrestricted_port_request;
unrestricted_port_request.method = "GET";
unrestricted_port_request.url = GURL("https://www.example.org:1024/");
unrestricted_port_request.load_flags = 0;
unrestricted_port_request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockConnect mock_connect(ASYNC, ERR_CONNECTION_REFUSED);
StaticSocketDataProvider first_data;
first_data.set_connect_data(mock_connect);
session_deps_.socket_factory->AddSocketDataProvider(&first_data);
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n\r\n"),
MockRead("hello world"),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider second_data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&second_data);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
const int kUnrestrictedAlternatePort = 1025;
AlternativeService alternative_service(kProtoHTTP2, "www.example.org",
kUnrestrictedAlternatePort);
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
http_server_properties->SetHttp2AlternativeService(
url::SchemeHostPort(unrestricted_port_request.url), alternative_service,
expiration);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&unrestricted_port_request, callback.callback(),
NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// Valid change to an unrestricted port should pass.
EXPECT_THAT(callback.WaitForResult(), IsOk());
}
// Ensure that we are not allowed to redirect traffic via an alternate protocol
// to an unsafe port, and that we resume the second HttpStreamFactory::Job once
// the alternate protocol request fails.
TEST_F(HttpNetworkTransactionTest, AlternateProtocolUnsafeBlocked) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// The alternate protocol request will error out before we attempt to connect,
// so only the standard HTTP request will try to connect.
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n\r\n"),
MockRead("hello world"),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
const int kUnsafePort = 7;
AlternativeService alternative_service(kProtoHTTP2, "www.example.org",
kUnsafePort);
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
http_server_properties->SetHttp2AlternativeService(
url::SchemeHostPort(request.url), alternative_service, expiration);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// The HTTP request should succeed.
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
}
TEST_F(HttpNetworkTransactionTest, UseAlternateProtocolForNpnSpdy) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead(kAlternativeServiceHttpHeader),
MockRead("\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
MockRead(ASYNC, OK)};
StaticSocketDataProvider first_transaction(data_reads,
base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&first_transaction);
SSLSocketDataProvider ssl_http11(ASYNC, OK);
ssl_http11.next_proto = kProtoHTTP11;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_http11);
AddSSLSocketData();
spdy::SpdySerializedFrame req(
spdy_util_.ConstructSpdyGet("https://www.example.org/", 1, LOWEST));
MockWrite spdy_writes[] = {CreateMockWrite(req, 0)};
spdy::SpdySerializedFrame resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame data(spdy_util_.ConstructSpdyDataFrame(1, true));
MockRead spdy_reads[] = {
CreateMockRead(resp, 1), CreateMockRead(data, 2), MockRead(ASYNC, 0, 3),
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
MockConnect never_finishing_connect(SYNCHRONOUS, ERR_IO_PENDING);
StaticSocketDataProvider hanging_non_alternate_protocol_socket;
hanging_non_alternate_protocol_socket.set_connect_data(
never_finishing_connect);
session_deps_.socket_factory->AddSocketDataProvider(
&hanging_non_alternate_protocol_socket);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
std::string response_data;
ASSERT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
ASSERT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
}
TEST_F(HttpNetworkTransactionTest, AlternateProtocolWithSpdyLateBinding) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// First transaction receives Alt-Svc header over HTTP/1.1.
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead(kAlternativeServiceHttpHeader),
MockRead("\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider http11_data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&http11_data);
SSLSocketDataProvider ssl_http11(ASYNC, OK);
ssl_http11.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "wildcard.pem");
ASSERT_TRUE(ssl_http11.ssl_info.cert);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_http11);
// Second transaction starts an alternative and a non-alternative Job.
// Both sockets hang.
MockConnect never_finishing_connect(SYNCHRONOUS, ERR_IO_PENDING);
StaticSocketDataProvider hanging_socket1;
hanging_socket1.set_connect_data(never_finishing_connect);
session_deps_.socket_factory->AddSocketDataProvider(&hanging_socket1);
StaticSocketDataProvider hanging_socket2;
hanging_socket2.set_connect_data(never_finishing_connect);
session_deps_.socket_factory->AddSocketDataProvider(&hanging_socket2);
// Third transaction starts an alternative and a non-alternative job.
// The non-alternative job hangs, but the alternative one succeeds.
// The second transaction, still pending, binds to this socket.
spdy::SpdySerializedFrame req1(
spdy_util_.ConstructSpdyGet("https://www.example.org/", 1, LOWEST));
spdy::SpdySerializedFrame req2(
spdy_util_.ConstructSpdyGet("https://www.example.org/", 3, LOWEST));
MockWrite spdy_writes[] = {
CreateMockWrite(req1, 0), CreateMockWrite(req2, 1),
};
spdy::SpdySerializedFrame resp1(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame data1(spdy_util_.ConstructSpdyDataFrame(1, true));
spdy::SpdySerializedFrame resp2(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 3));
spdy::SpdySerializedFrame data2(spdy_util_.ConstructSpdyDataFrame(3, true));
MockRead spdy_reads[] = {
CreateMockRead(resp1, 2), CreateMockRead(data1, 3),
CreateMockRead(resp2, 4), CreateMockRead(data2, 5),
MockRead(ASYNC, 0, 6),
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
AddSSLSocketData();
StaticSocketDataProvider hanging_socket3;
hanging_socket3.set_connect_data(never_finishing_connect);
session_deps_.socket_factory->AddSocketDataProvider(&hanging_socket3);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
TestCompletionCallback callback1;
HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
int rv = trans1.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback1.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans1.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans1, &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
TestCompletionCallback callback2;
HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
rv = trans2.Start(&request, callback2.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
TestCompletionCallback callback3;
HttpNetworkTransaction trans3(DEFAULT_PRIORITY, session.get());
rv = trans3.Start(&request, callback3.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback2.WaitForResult(), IsOk());
EXPECT_THAT(callback3.WaitForResult(), IsOk());
response = trans2.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
ASSERT_THAT(ReadTransaction(&trans2, &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
response = trans3.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
ASSERT_THAT(ReadTransaction(&trans3, &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
}
TEST_F(HttpNetworkTransactionTest, StallAlternativeServiceForNpnSpdy) {
session_deps_.host_resolver->set_synchronous_mode(true);
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead(kAlternativeServiceHttpHeader),
MockRead("\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider first_transaction(data_reads,
base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&first_transaction);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "wildcard.pem");
ASSERT_TRUE(ssl.ssl_info.cert);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
MockConnect never_finishing_connect(SYNCHRONOUS, ERR_IO_PENDING);
StaticSocketDataProvider hanging_alternate_protocol_socket;
hanging_alternate_protocol_socket.set_connect_data(
never_finishing_connect);
session_deps_.socket_factory->AddSocketDataProvider(
&hanging_alternate_protocol_socket);
// 2nd request is just a copy of the first one, over HTTP/1.1 again.
StaticSocketDataProvider second_transaction(data_reads,
base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&second_transaction);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
std::string response_data;
ASSERT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
EXPECT_FALSE(response->was_fetched_via_spdy);
EXPECT_FALSE(response->was_alpn_negotiated);
ASSERT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
}
// Test that proxy is resolved using the origin url,
// regardless of the alternative server.
TEST_F(HttpNetworkTransactionTest, UseOriginNotAlternativeForProxy) {
// Configure proxy to bypass www.example.org, which is the origin URL.
ProxyConfig proxy_config;
proxy_config.proxy_rules().ParseFromString("myproxy:70");
proxy_config.proxy_rules().bypass_rules.AddRuleFromString("www.example.org");
auto proxy_config_service = std::make_unique<ProxyConfigServiceFixed>(
ProxyConfigWithAnnotation(proxy_config, TRAFFIC_ANNOTATION_FOR_TESTS));
CapturingProxyResolver capturing_proxy_resolver;
auto proxy_resolver_factory = std::make_unique<CapturingProxyResolverFactory>(
&capturing_proxy_resolver);
TestNetLog net_log;
session_deps_.proxy_resolution_service =
std::make_unique<ProxyResolutionService>(
std::move(proxy_config_service), std::move(proxy_resolver_factory),
&net_log);
session_deps_.net_log = &net_log;
// Configure alternative service with a hostname that is not bypassed by the
// proxy.
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
url::SchemeHostPort server("https", "www.example.org", 443);
HostPortPair alternative("www.example.com", 443);
AlternativeService alternative_service(kProtoHTTP2, alternative);
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
http_server_properties->SetHttp2AlternativeService(
server, alternative_service, expiration);
// Non-alternative job should hang.
MockConnect never_finishing_connect(SYNCHRONOUS, ERR_IO_PENDING);
StaticSocketDataProvider hanging_alternate_protocol_socket;
hanging_alternate_protocol_socket.set_connect_data(never_finishing_connect);
session_deps_.socket_factory->AddSocketDataProvider(
&hanging_alternate_protocol_socket);
AddSSLSocketData();
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.load_flags = 0;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
spdy::SpdySerializedFrame req(
spdy_util_.ConstructSpdyGet("https://www.example.org/", 1, LOWEST));
MockWrite spdy_writes[] = {CreateMockWrite(req, 0)};
spdy::SpdySerializedFrame resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame data(spdy_util_.ConstructSpdyDataFrame(1, true));
MockRead spdy_reads[] = {
CreateMockRead(resp, 1), CreateMockRead(data, 2), MockRead(ASYNC, 0, 3),
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
TestCompletionCallback callback;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
// Origin host bypasses proxy, no resolution should have happened.
ASSERT_TRUE(capturing_proxy_resolver.resolved().empty());
}
TEST_F(HttpNetworkTransactionTest, UseAlternativeServiceForTunneledNpnSpdy) {
ProxyConfig proxy_config;
proxy_config.set_auto_detect(true);
proxy_config.set_pac_url(GURL("http://fooproxyurl"));
CapturingProxyResolver capturing_proxy_resolver;
session_deps_.proxy_resolution_service =
std::make_unique<ProxyResolutionService>(
std::make_unique<ProxyConfigServiceFixed>(ProxyConfigWithAnnotation(
proxy_config, TRAFFIC_ANNOTATION_FOR_TESTS)),
std::make_unique<CapturingProxyResolverFactory>(
&capturing_proxy_resolver),
nullptr);
TestNetLog net_log;
session_deps_.net_log = &net_log;
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead(kAlternativeServiceHttpHeader),
MockRead("\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider first_transaction(data_reads,
base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&first_transaction);
SSLSocketDataProvider ssl_http11(ASYNC, OK);
ssl_http11.next_proto = kProtoHTTP11;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_http11);
AddSSLSocketData();
spdy::SpdySerializedFrame req(
spdy_util_.ConstructSpdyGet("https://www.example.org/", 1, LOWEST));
MockWrite spdy_writes[] = {
MockWrite(ASYNC, 0,
"CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
CreateMockWrite(req, 2),
};
const char kCONNECTResponse[] = "HTTP/1.1 200 Connected\r\n\r\n";
spdy::SpdySerializedFrame resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame data(spdy_util_.ConstructSpdyDataFrame(1, true));
MockRead spdy_reads[] = {
MockRead(ASYNC, 1, kCONNECTResponse), CreateMockRead(resp, 3),
CreateMockRead(data, 4), MockRead(SYNCHRONOUS, ERR_IO_PENDING, 5),
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
MockConnect never_finishing_connect(SYNCHRONOUS, ERR_IO_PENDING);
StaticSocketDataProvider hanging_non_alternate_protocol_socket;
hanging_non_alternate_protocol_socket.set_connect_data(
never_finishing_connect);
session_deps_.socket_factory->AddSocketDataProvider(
&hanging_non_alternate_protocol_socket);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/0.9 200 OK", response->headers->GetStatusLine());
EXPECT_FALSE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
std::string response_data;
ASSERT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
ASSERT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
ASSERT_EQ(2u, capturing_proxy_resolver.resolved().size());
EXPECT_EQ("https://www.example.org/",
capturing_proxy_resolver.resolved()[0].spec());
EXPECT_EQ("https://www.example.org/",
capturing_proxy_resolver.resolved()[1].spec());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans->GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReusedWithPac(load_timing_info,
CONNECT_TIMING_HAS_SSL_TIMES);
}
TEST_F(HttpNetworkTransactionTest,
UseAlternativeServiceForNpnSpdyWithExistingSpdySession) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead(kAlternativeServiceHttpHeader),
MockRead("\r\n"),
MockRead("hello world"),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider first_transaction(data_reads,
base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&first_transaction);
SSLSocketDataProvider ssl_http11(ASYNC, OK);
ssl_http11.next_proto = kProtoHTTP11;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_http11);
AddSSLSocketData();
spdy::SpdySerializedFrame req(
spdy_util_.ConstructSpdyGet("https://www.example.org/", 1, LOWEST));
MockWrite spdy_writes[] = {CreateMockWrite(req, 0)};
spdy::SpdySerializedFrame resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame data(spdy_util_.ConstructSpdyDataFrame(1, true));
MockRead spdy_reads[] = {
CreateMockRead(resp, 1), CreateMockRead(data, 2), MockRead(ASYNC, 0, 3),
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
std::string response_data;
ASSERT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
// Set up an initial SpdySession in the pool to reuse.
HostPortPair host_port_pair("www.example.org", 443);
SpdySessionKey key(host_port_pair, ProxyServer::Direct(),
PRIVACY_MODE_DISABLED,
SpdySessionKey::IsProxySession::kFalse, SocketTag());
base::WeakPtr<SpdySession> spdy_session =
CreateSpdySession(session.get(), key, NetLogWithSource());
trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
ASSERT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
}
// GenerateAuthToken is a mighty big test.
// It tests all permutation of GenerateAuthToken behavior:
// - Synchronous and Asynchronous completion.
// - OK or error on completion.
// - Direct connection, non-authenticating proxy, and authenticating proxy.
// - HTTP or HTTPS backend (to include proxy tunneling).
// - Non-authenticating and authenticating backend.
//
// In all, there are 44 reasonable permuations (for example, if there are
// problems generating an auth token for an authenticating proxy, we don't
// need to test all permutations of the backend server).
//
// The test proceeds by going over each of the configuration cases, and
// potentially running up to three rounds in each of the tests. The TestConfig
// specifies both the configuration for the test as well as the expectations
// for the results.
TEST_F(HttpNetworkTransactionTest, GenerateAuthToken) {
static const char kServer[] = "http://www.example.com";
static const char kSecureServer[] = "https://www.example.com";
static const char kProxy[] = "myproxy:70";
enum AuthTiming {
AUTH_NONE,
AUTH_SYNC,
AUTH_ASYNC,
};
const MockWrite kGet(
"GET / HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Connection: keep-alive\r\n\r\n");
const MockWrite kGetProxy(
"GET http://www.example.com/ HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Proxy-Connection: keep-alive\r\n\r\n");
const MockWrite kGetAuth(
"GET / HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Connection: keep-alive\r\n"
"Authorization: auth_token\r\n\r\n");
const MockWrite kGetProxyAuth(
"GET http://www.example.com/ HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: auth_token\r\n\r\n");
const MockWrite kGetAuthThroughProxy(
"GET http://www.example.com/ HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Proxy-Connection: keep-alive\r\n"
"Authorization: auth_token\r\n\r\n");
const MockWrite kGetAuthWithProxyAuth(
"GET http://www.example.com/ HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: auth_token\r\n"
"Authorization: auth_token\r\n\r\n");
const MockWrite kConnect(
"CONNECT www.example.com:443 HTTP/1.1\r\n"
"Host: www.example.com:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n");
const MockWrite kConnectProxyAuth(
"CONNECT www.example.com:443 HTTP/1.1\r\n"
"Host: www.example.com:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: auth_token\r\n\r\n");
const MockRead kSuccess(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=iso-8859-1\r\n"
"Content-Length: 3\r\n\r\n"
"Yes");
const MockRead kFailure(
"Should not be called.");
const MockRead kServerChallenge(
"HTTP/1.1 401 Unauthorized\r\n"
"WWW-Authenticate: Mock realm=server\r\n"
"Content-Type: text/html; charset=iso-8859-1\r\n"
"Content-Length: 14\r\n\r\n"
"Unauthorized\r\n");
const MockRead kProxyChallenge(
"HTTP/1.1 407 Unauthorized\r\n"
"Proxy-Authenticate: Mock realm=proxy\r\n"
"Proxy-Connection: close\r\n"
"Content-Type: text/html; charset=iso-8859-1\r\n"
"Content-Length: 14\r\n\r\n"
"Unauthorized\r\n");
const MockRead kProxyConnected(
"HTTP/1.1 200 Connection Established\r\n\r\n");
// NOTE(cbentzel): I wanted TestReadWriteRound to be a simple struct with
// no constructors, but the C++ compiler on Windows warns about
// unspecified data in compound literals. So, moved to using constructors,
// and TestRound's created with the default constructor should not be used.
struct TestRound {
TestRound()
: expected_rv(ERR_UNEXPECTED),
extra_write(nullptr),
extra_read(nullptr) {}
TestRound(const MockWrite& write_arg,
const MockRead& read_arg,
int expected_rv_arg)
: write(write_arg),
read(read_arg),
expected_rv(expected_rv_arg),
extra_write(nullptr),
extra_read(nullptr) {}
TestRound(const MockWrite& write_arg, const MockRead& read_arg,
int expected_rv_arg, const MockWrite* extra_write_arg,
const MockRead* extra_read_arg)
: write(write_arg),
read(read_arg),
expected_rv(expected_rv_arg),
extra_write(extra_write_arg),
extra_read(extra_read_arg) {
}
MockWrite write;
MockRead read;
int expected_rv;
const MockWrite* extra_write;
const MockRead* extra_read;
};
static const int kNoSSL = 500;
struct TestConfig {
int line_number;
const char* const proxy_url;
AuthTiming proxy_auth_timing;
int first_generate_proxy_token_rv;
const char* const server_url;
AuthTiming server_auth_timing;
int first_generate_server_token_rv;
int num_auth_rounds;
int first_ssl_round;
TestRound rounds[4];
} test_configs[] = {
// Non-authenticating HTTP server with a direct connection.
{__LINE__,
nullptr,
AUTH_NONE,
OK,
kServer,
AUTH_NONE,
OK,
1,
kNoSSL,
{TestRound(kGet, kSuccess, OK)}},
// Authenticating HTTP server with a direct connection.
{__LINE__,
nullptr,
AUTH_NONE,
OK,
kServer,
AUTH_SYNC,
OK,
2,
kNoSSL,
{TestRound(kGet, kServerChallenge, OK),
TestRound(kGetAuth, kSuccess, OK)}},
{__LINE__,
nullptr,
AUTH_NONE,
OK,
kServer,
AUTH_SYNC,
ERR_INVALID_AUTH_CREDENTIALS,
3,
kNoSSL,
{TestRound(kGet, kServerChallenge, OK),
TestRound(kGet, kServerChallenge, OK),
TestRound(kGetAuth, kSuccess, OK)}},
{__LINE__,
nullptr,
AUTH_NONE,
OK,
kServer,
AUTH_SYNC,
ERR_UNSUPPORTED_AUTH_SCHEME,
2,
kNoSSL,
{TestRound(kGet, kServerChallenge, OK), TestRound(kGet, kSuccess, OK)}},
{__LINE__,
nullptr,
AUTH_NONE,
OK,
kServer,
AUTH_SYNC,
ERR_UNDOCUMENTED_SECURITY_LIBRARY_STATUS,
2,
kNoSSL,
{TestRound(kGet, kServerChallenge, OK), TestRound(kGet, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_SYNC,
ERR_FAILED,
kServer,
AUTH_NONE,
OK,
2,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxy, kFailure, ERR_FAILED)}},
{__LINE__,
kProxy,
AUTH_ASYNC,
ERR_FAILED,
kServer,
AUTH_NONE,
OK,
2,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxy, kFailure, ERR_FAILED)}},
{__LINE__,
nullptr,
AUTH_NONE,
OK,
kServer,
AUTH_SYNC,
ERR_FAILED,
2,
kNoSSL,
{TestRound(kGet, kServerChallenge, OK),
TestRound(kGet, kFailure, ERR_FAILED)}},
{__LINE__,
nullptr,
AUTH_NONE,
OK,
kServer,
AUTH_ASYNC,
ERR_FAILED,
2,
kNoSSL,
{TestRound(kGet, kServerChallenge, OK),
TestRound(kGet, kFailure, ERR_FAILED)}},
{__LINE__,
nullptr,
AUTH_NONE,
OK,
kServer,
AUTH_ASYNC,
OK,
2,
kNoSSL,
{TestRound(kGet, kServerChallenge, OK),
TestRound(kGetAuth, kSuccess, OK)}},
{__LINE__,
nullptr,
AUTH_NONE,
OK,
kServer,
AUTH_ASYNC,
ERR_INVALID_AUTH_CREDENTIALS,
3,
kNoSSL,
{TestRound(kGet, kServerChallenge, OK),
// The second round uses a HttpAuthHandlerMock that always succeeds.
TestRound(kGet, kServerChallenge, OK),
TestRound(kGetAuth, kSuccess, OK)}},
// Non-authenticating HTTP server through a non-authenticating proxy.
{__LINE__,
kProxy,
AUTH_NONE,
OK,
kServer,
AUTH_NONE,
OK,
1,
kNoSSL,
{TestRound(kGetProxy, kSuccess, OK)}},
// Authenticating HTTP server through a non-authenticating proxy.
{__LINE__,
kProxy,
AUTH_NONE,
OK,
kServer,
AUTH_SYNC,
OK,
2,
kNoSSL,
{TestRound(kGetProxy, kServerChallenge, OK),
TestRound(kGetAuthThroughProxy, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_NONE,
OK,
kServer,
AUTH_SYNC,
ERR_INVALID_AUTH_CREDENTIALS,
3,
kNoSSL,
{TestRound(kGetProxy, kServerChallenge, OK),
TestRound(kGetProxy, kServerChallenge, OK),
TestRound(kGetAuthThroughProxy, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_NONE,
OK,
kServer,
AUTH_ASYNC,
OK,
2,
kNoSSL,
{TestRound(kGetProxy, kServerChallenge, OK),
TestRound(kGetAuthThroughProxy, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_NONE,
OK,
kServer,
AUTH_ASYNC,
ERR_INVALID_AUTH_CREDENTIALS,
2,
kNoSSL,
{TestRound(kGetProxy, kServerChallenge, OK),
TestRound(kGetProxy, kSuccess, OK)}},
// Non-authenticating HTTP server through an authenticating proxy.
{__LINE__,
kProxy,
AUTH_SYNC,
OK,
kServer,
AUTH_NONE,
OK,
2,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxyAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_SYNC,
ERR_INVALID_AUTH_CREDENTIALS,
kServer,
AUTH_NONE,
OK,
2,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxy, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_ASYNC,
OK,
kServer,
AUTH_NONE,
OK,
2,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxyAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_ASYNC,
ERR_INVALID_AUTH_CREDENTIALS,
kServer,
AUTH_NONE,
OK,
2,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxy, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_ASYNC,
ERR_INVALID_AUTH_CREDENTIALS,
kServer,
AUTH_NONE,
OK,
3,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxyAuth, kSuccess, OK)}},
// Authenticating HTTP server through an authenticating proxy.
{__LINE__,
kProxy,
AUTH_SYNC,
OK,
kServer,
AUTH_SYNC,
OK,
3,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxyAuth, kServerChallenge, OK),
TestRound(kGetAuthWithProxyAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_SYNC,
OK,
kServer,
AUTH_SYNC,
ERR_INVALID_AUTH_CREDENTIALS,
3,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxyAuth, kServerChallenge, OK),
TestRound(kGetProxyAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_ASYNC,
OK,
kServer,
AUTH_SYNC,
OK,
3,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxyAuth, kServerChallenge, OK),
TestRound(kGetAuthWithProxyAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_ASYNC,
OK,
kServer,
AUTH_SYNC,
ERR_INVALID_AUTH_CREDENTIALS,
3,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxyAuth, kServerChallenge, OK),
TestRound(kGetProxyAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_SYNC,
OK,
kServer,
AUTH_ASYNC,
OK,
3,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxyAuth, kServerChallenge, OK),
TestRound(kGetAuthWithProxyAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_SYNC,
ERR_INVALID_AUTH_CREDENTIALS,
kServer,
AUTH_ASYNC,
OK,
4,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxyAuth, kServerChallenge, OK),
TestRound(kGetAuthWithProxyAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_SYNC,
OK,
kServer,
AUTH_ASYNC,
ERR_INVALID_AUTH_CREDENTIALS,
3,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxyAuth, kServerChallenge, OK),
TestRound(kGetProxyAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_ASYNC,
OK,
kServer,
AUTH_ASYNC,
OK,
3,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxyAuth, kServerChallenge, OK),
TestRound(kGetAuthWithProxyAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_ASYNC,
OK,
kServer,
AUTH_ASYNC,
ERR_INVALID_AUTH_CREDENTIALS,
3,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxyAuth, kServerChallenge, OK),
TestRound(kGetProxyAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_ASYNC,
ERR_INVALID_AUTH_CREDENTIALS,
kServer,
AUTH_ASYNC,
ERR_INVALID_AUTH_CREDENTIALS,
4,
kNoSSL,
{TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxy, kProxyChallenge, OK),
TestRound(kGetProxyAuth, kServerChallenge, OK),
TestRound(kGetProxyAuth, kSuccess, OK)}},
// Non-authenticating HTTPS server with a direct connection.
{__LINE__,
nullptr,
AUTH_NONE,
OK,
kSecureServer,
AUTH_NONE,
OK,
1,
0,
{TestRound(kGet, kSuccess, OK)}},
// Authenticating HTTPS server with a direct connection.
{__LINE__,
nullptr,
AUTH_NONE,
OK,
kSecureServer,
AUTH_SYNC,
OK,
2,
0,
{TestRound(kGet, kServerChallenge, OK),
TestRound(kGetAuth, kSuccess, OK)}},
{__LINE__,
nullptr,
AUTH_NONE,
OK,
kSecureServer,
AUTH_SYNC,
ERR_INVALID_AUTH_CREDENTIALS,
2,
0,
{TestRound(kGet, kServerChallenge, OK), TestRound(kGet, kSuccess, OK)}},
{__LINE__,
nullptr,
AUTH_NONE,
OK,
kSecureServer,
AUTH_ASYNC,
OK,
2,
0,
{TestRound(kGet, kServerChallenge, OK),
TestRound(kGetAuth, kSuccess, OK)}},
{__LINE__,
nullptr,
AUTH_NONE,
OK,
kSecureServer,
AUTH_ASYNC,
ERR_INVALID_AUTH_CREDENTIALS,
2,
0,
{TestRound(kGet, kServerChallenge, OK), TestRound(kGet, kSuccess, OK)}},
// Non-authenticating HTTPS server with a non-authenticating proxy.
{__LINE__,
kProxy,
AUTH_NONE,
OK,
kSecureServer,
AUTH_NONE,
OK,
1,
0,
{TestRound(kConnect, kProxyConnected, OK, &kGet, &kSuccess)}},
// Authenticating HTTPS server through a non-authenticating proxy.
{__LINE__,
kProxy,
AUTH_NONE,
OK,
kSecureServer,
AUTH_SYNC,
OK,
2,
0,
{TestRound(kConnect, kProxyConnected, OK, &kGet, &kServerChallenge),
TestRound(kGetAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_NONE,
OK,
kSecureServer,
AUTH_SYNC,
ERR_INVALID_AUTH_CREDENTIALS,
2,
0,
{TestRound(kConnect, kProxyConnected, OK, &kGet, &kServerChallenge),
TestRound(kGet, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_NONE,
OK,
kSecureServer,
AUTH_ASYNC,
OK,
2,
0,
{TestRound(kConnect, kProxyConnected, OK, &kGet, &kServerChallenge),
TestRound(kGetAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_NONE,
OK,
kSecureServer,
AUTH_ASYNC,
ERR_INVALID_AUTH_CREDENTIALS,
2,
0,
{TestRound(kConnect, kProxyConnected, OK, &kGet, &kServerChallenge),
TestRound(kGet, kSuccess, OK)}},
// Non-Authenticating HTTPS server through an authenticating proxy.
{__LINE__,
kProxy,
AUTH_SYNC,
OK,
kSecureServer,
AUTH_NONE,
OK,
2,
1,
{TestRound(kConnect, kProxyChallenge, OK),
TestRound(kConnectProxyAuth, kProxyConnected, OK, &kGet, &kSuccess)}},
{__LINE__,
kProxy,
AUTH_SYNC,
ERR_INVALID_AUTH_CREDENTIALS,
kSecureServer,
AUTH_NONE,
OK,
2,
kNoSSL,
{TestRound(kConnect, kProxyChallenge, OK),
TestRound(kConnect, kProxyConnected, OK, &kGet, &kSuccess)}},
{__LINE__,
kProxy,
AUTH_SYNC,
ERR_UNSUPPORTED_AUTH_SCHEME,
kSecureServer,
AUTH_NONE,
OK,
2,
kNoSSL,
{TestRound(kConnect, kProxyChallenge, OK),
TestRound(kConnect, kProxyConnected, OK, &kGet, &kSuccess)}},
{__LINE__,
kProxy,
AUTH_SYNC,
ERR_UNEXPECTED,
kSecureServer,
AUTH_NONE,
OK,
2,
kNoSSL,
{TestRound(kConnect, kProxyChallenge, OK),
TestRound(kConnect, kProxyConnected, ERR_UNEXPECTED)}},
{__LINE__,
kProxy,
AUTH_ASYNC,
OK,
kSecureServer,
AUTH_NONE,
OK,
2,
1,
{TestRound(kConnect, kProxyChallenge, OK),
TestRound(kConnectProxyAuth, kProxyConnected, OK, &kGet, &kSuccess)}},
{__LINE__,
kProxy,
AUTH_ASYNC,
ERR_INVALID_AUTH_CREDENTIALS,
kSecureServer,
AUTH_NONE,
OK,
2,
kNoSSL,
{TestRound(kConnect, kProxyChallenge, OK),
TestRound(kConnect, kProxyConnected, OK, &kGet, &kSuccess)}},
// Authenticating HTTPS server through an authenticating proxy.
{__LINE__,
kProxy,
AUTH_SYNC,
OK,
kSecureServer,
AUTH_SYNC,
OK,
3,
1,
{TestRound(kConnect, kProxyChallenge, OK),
TestRound(kConnectProxyAuth, kProxyConnected, OK, &kGet,
&kServerChallenge),
TestRound(kGetAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_SYNC,
OK,
kSecureServer,
AUTH_SYNC,
ERR_INVALID_AUTH_CREDENTIALS,
3,
1,
{TestRound(kConnect, kProxyChallenge, OK),
TestRound(kConnectProxyAuth, kProxyConnected, OK, &kGet,
&kServerChallenge),
TestRound(kGet, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_ASYNC,
OK,
kSecureServer,
AUTH_SYNC,
OK,
3,
1,
{TestRound(kConnect, kProxyChallenge, OK),
TestRound(kConnectProxyAuth, kProxyConnected, OK, &kGet,
&kServerChallenge),
TestRound(kGetAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_ASYNC,
OK,
kSecureServer,
AUTH_SYNC,
ERR_INVALID_AUTH_CREDENTIALS,
3,
1,
{TestRound(kConnect, kProxyChallenge, OK),
TestRound(kConnectProxyAuth, kProxyConnected, OK, &kGet,
&kServerChallenge),
TestRound(kGet, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_SYNC,
OK,
kSecureServer,
AUTH_ASYNC,
OK,
3,
1,
{TestRound(kConnect, kProxyChallenge, OK),
TestRound(kConnectProxyAuth, kProxyConnected, OK, &kGet,
&kServerChallenge),
TestRound(kGetAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_SYNC,
OK,
kSecureServer,
AUTH_ASYNC,
ERR_INVALID_AUTH_CREDENTIALS,
3,
1,
{TestRound(kConnect, kProxyChallenge, OK),
TestRound(kConnectProxyAuth, kProxyConnected, OK, &kGet,
&kServerChallenge),
TestRound(kGet, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_ASYNC,
OK,
kSecureServer,
AUTH_ASYNC,
OK,
3,
1,
{TestRound(kConnect, kProxyChallenge, OK),
TestRound(kConnectProxyAuth, kProxyConnected, OK, &kGet,
&kServerChallenge),
TestRound(kGetAuth, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_ASYNC,
OK,
kSecureServer,
AUTH_ASYNC,
ERR_INVALID_AUTH_CREDENTIALS,
3,
1,
{TestRound(kConnect, kProxyChallenge, OK),
TestRound(kConnectProxyAuth, kProxyConnected, OK, &kGet,
&kServerChallenge),
TestRound(kGet, kSuccess, OK)}},
{__LINE__,
kProxy,
AUTH_ASYNC,
ERR_INVALID_AUTH_CREDENTIALS,
kSecureServer,
AUTH_ASYNC,
ERR_INVALID_AUTH_CREDENTIALS,
4,
2,
{TestRound(kConnect, kProxyChallenge, OK),
TestRound(kConnect, kProxyChallenge, OK),
TestRound(kConnectProxyAuth, kProxyConnected, OK, &kGet,
&kServerChallenge),
TestRound(kGet, kSuccess, OK)}},
};
for (const auto& test_config : test_configs) {
SCOPED_TRACE(::testing::Message() << "Test config at "
<< test_config.line_number);
HttpAuthHandlerMock::Factory* auth_factory(
new HttpAuthHandlerMock::Factory());
session_deps_.http_auth_handler_factory.reset(auth_factory);
SSLInfo empty_ssl_info;
// Set up authentication handlers as necessary.
if (test_config.proxy_auth_timing != AUTH_NONE) {
for (int n = 0; n < 3; n++) {
HttpAuthHandlerMock* auth_handler(new HttpAuthHandlerMock());
std::string auth_challenge = "Mock realm=proxy";
GURL origin(test_config.proxy_url);
HttpAuthChallengeTokenizer tokenizer(auth_challenge.begin(),
auth_challenge.end());
auth_handler->InitFromChallenge(&tokenizer, HttpAuth::AUTH_PROXY,
empty_ssl_info, origin,
NetLogWithSource());
auth_handler->SetGenerateExpectation(
test_config.proxy_auth_timing == AUTH_ASYNC,
n == 0 ? test_config.first_generate_proxy_token_rv : OK);
auth_factory->AddMockHandler(auth_handler, HttpAuth::AUTH_PROXY);
}
}
if (test_config.server_auth_timing != AUTH_NONE) {
HttpAuthHandlerMock* auth_handler(new HttpAuthHandlerMock());
std::string auth_challenge = "Mock realm=server";
GURL origin(test_config.server_url);
HttpAuthChallengeTokenizer tokenizer(auth_challenge.begin(),
auth_challenge.end());
auth_handler->InitFromChallenge(&tokenizer, HttpAuth::AUTH_SERVER,
empty_ssl_info, origin,
NetLogWithSource());
auth_handler->SetGenerateExpectation(
test_config.server_auth_timing == AUTH_ASYNC,
test_config.first_generate_server_token_rv);
auth_factory->AddMockHandler(auth_handler, HttpAuth::AUTH_SERVER);
// The second handler always succeeds. It should only be used where there
// are multiple auth sessions for server auth in the same network
// transaction using the same auth scheme.
std::unique_ptr<HttpAuthHandlerMock> second_handler =
std::make_unique<HttpAuthHandlerMock>();
second_handler->InitFromChallenge(&tokenizer, HttpAuth::AUTH_SERVER,
empty_ssl_info, origin,
NetLogWithSource());
second_handler->SetGenerateExpectation(true, OK);
auth_factory->AddMockHandler(second_handler.release(),
HttpAuth::AUTH_SERVER);
}
if (test_config.proxy_url) {
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixed(test_config.proxy_url,
TRAFFIC_ANNOTATION_FOR_TESTS);
} else {
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateDirect();
}
HttpRequestInfo request;
request.method = "GET";
request.url = GURL(test_config.server_url);
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
SSLSocketDataProvider ssl_socket_data_provider(SYNCHRONOUS, OK);
std::vector<std::vector<MockRead>> mock_reads(1);
std::vector<std::vector<MockWrite>> mock_writes(1);
for (int round = 0; round < test_config.num_auth_rounds; ++round) {
SCOPED_TRACE(round);
const TestRound& read_write_round = test_config.rounds[round];
// Set up expected reads and writes.
mock_reads.back().push_back(read_write_round.read);
mock_writes.back().push_back(read_write_round.write);
// kProxyChallenge uses Proxy-Connection: close which means that the
// socket is closed and a new one will be created for the next request.
if (read_write_round.read.data == kProxyChallenge.data) {
mock_reads.push_back(std::vector<MockRead>());
mock_writes.push_back(std::vector<MockWrite>());
}
if (read_write_round.extra_read) {
mock_reads.back().push_back(*read_write_round.extra_read);
}
if (read_write_round.extra_write) {
mock_writes.back().push_back(*read_write_round.extra_write);
}
// Add an SSL sequence if necessary.
if (round >= test_config.first_ssl_round)
session_deps_.socket_factory->AddSSLSocketDataProvider(
&ssl_socket_data_provider);
}
std::vector<std::unique_ptr<StaticSocketDataProvider>> data_providers;
for (size_t i = 0; i < mock_reads.size(); ++i) {
data_providers.push_back(std::make_unique<StaticSocketDataProvider>(
mock_reads[i], mock_writes[i]));
session_deps_.socket_factory->AddSocketDataProvider(
data_providers.back().get());
}
// Transaction must be created after DataProviders, so it's destroyed before
// they are as well.
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
for (int round = 0; round < test_config.num_auth_rounds; ++round) {
SCOPED_TRACE(round);
const TestRound& read_write_round = test_config.rounds[round];
// Start or restart the transaction.
TestCompletionCallback callback;
int rv;
if (round == 0) {
rv = trans.Start(&request, callback.callback(), NetLogWithSource());
} else {
rv = trans.RestartWithAuth(
AuthCredentials(kFoo, kBar), callback.callback());
}
if (rv == ERR_IO_PENDING)
rv = callback.WaitForResult();
// Compare results with expected data.
EXPECT_THAT(rv, IsError(read_write_round.expected_rv));
const HttpResponseInfo* response = trans.GetResponseInfo();
if (read_write_round.expected_rv != OK) {
EXPECT_EQ(round + 1, test_config.num_auth_rounds);
continue;
}
if (round + 1 < test_config.num_auth_rounds) {
EXPECT_TRUE(response->auth_challenge.has_value());
} else {
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_FALSE(trans.IsReadyToRestartForAuth());
}
}
}
}
TEST_F(HttpNetworkTransactionTest, MultiRoundAuth) {
// Do multi-round authentication and make sure it works correctly.
HttpAuthHandlerMock::Factory* auth_factory(
new HttpAuthHandlerMock::Factory());
session_deps_.http_auth_handler_factory.reset(auth_factory);
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateDirect();
session_deps_.host_resolver->rules()->AddRule("www.example.com", "10.0.0.1");
HttpAuthHandlerMock* auth_handler(new HttpAuthHandlerMock());
auth_handler->set_connection_based(true);
std::string auth_challenge = "Mock realm=server";
GURL origin("http://www.example.com");
HttpAuthChallengeTokenizer tokenizer(auth_challenge.begin(),
auth_challenge.end());
SSLInfo empty_ssl_info;
auth_handler->InitFromChallenge(&tokenizer, HttpAuth::AUTH_SERVER,
empty_ssl_info, origin, NetLogWithSource());
auth_factory->AddMockHandler(auth_handler, HttpAuth::AUTH_SERVER);
int rv = OK;
const HttpResponseInfo* response = nullptr;
HttpRequestInfo request;
request.method = "GET";
request.url = origin;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Use a TCP Socket Pool with only one connection per group. This is used
// to validate that the TCP socket is not released to the pool between
// each round of multi-round authentication.
HttpNetworkSessionPeer session_peer(session.get());
CommonConnectJobParams common_connect_job_params(
session->CreateCommonConnectJobParams());
TransportClientSocketPool* transport_pool = new TransportClientSocketPool(
50, // Max sockets for pool
1, // Max sockets per group
base::TimeDelta::FromSeconds(10), // unused_idle_socket_timeout
ProxyServer::Direct(), false, // is_for_websockets
&common_connect_job_params, session_deps_.ssl_config_service.get());
auto mock_pool_manager = std::make_unique<MockClientSocketPoolManager>();
mock_pool_manager->SetSocketPool(ProxyServer::Direct(),
base::WrapUnique(transport_pool));
session_peer.SetClientSocketPoolManager(std::move(mock_pool_manager));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
const MockWrite kGet(
"GET / HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Connection: keep-alive\r\n\r\n");
const MockWrite kGetAuth(
"GET / HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Connection: keep-alive\r\n"
"Authorization: auth_token\r\n\r\n");
const MockRead kServerChallenge(
"HTTP/1.1 401 Unauthorized\r\n"
"WWW-Authenticate: Mock realm=server\r\n"
"Content-Type: text/html; charset=iso-8859-1\r\n"
"Content-Length: 14\r\n\r\n"
"Unauthorized\r\n");
const MockRead kSuccess(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=iso-8859-1\r\n"
"Content-Length: 3\r\n\r\n"
"Yes");
MockWrite writes[] = {
// First round
kGet,
// Second round
kGetAuth,
// Third round
kGetAuth,
// Fourth round
kGetAuth,
// Competing request
kGet,
};
MockRead reads[] = {
// First round
kServerChallenge,
// Second round
kServerChallenge,
// Third round
kServerChallenge,
// Fourth round
kSuccess,
// Competing response
kSuccess,
};
StaticSocketDataProvider data_provider(reads, writes);
session_deps_.socket_factory->AddSocketDataProvider(&data_provider);
const ClientSocketPool::GroupId kSocketGroup(
HostPortPair("www.example.com", 80), ClientSocketPool::SocketType::kHttp,
PrivacyMode::PRIVACY_MODE_DISABLED);
// First round of authentication.
auth_handler->SetGenerateExpectation(false, OK);
rv = trans.Start(&request, callback.callback(), NetLogWithSource());
if (rv == ERR_IO_PENDING)
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->auth_challenge.has_value());
EXPECT_EQ(0u, transport_pool->IdleSocketCountInGroup(kSocketGroup));
EXPECT_EQ(HttpAuthHandlerMock::State::WAIT_FOR_GENERATE_AUTH_TOKEN,
auth_handler->state());
// In between rounds, another request comes in for the same domain.
// It should not be able to grab the TCP socket that trans has already
// claimed.
HttpNetworkTransaction trans_compete(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback_compete;
rv = trans_compete.Start(&request, callback_compete.callback(),
NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// callback_compete.WaitForResult at this point would stall forever,
// since the HttpNetworkTransaction does not release the request back to
// the pool until after authentication completes.
// Second round of authentication.
auth_handler->SetGenerateExpectation(false, OK);
rv = trans.RestartWithAuth(AuthCredentials(kFoo, kBar), callback.callback());
if (rv == ERR_IO_PENDING)
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(0u, transport_pool->IdleSocketCountInGroup(kSocketGroup));
EXPECT_EQ(HttpAuthHandlerMock::State::WAIT_FOR_GENERATE_AUTH_TOKEN,
auth_handler->state());
// Third round of authentication.
auth_handler->SetGenerateExpectation(false, OK);
rv = trans.RestartWithAuth(AuthCredentials(), callback.callback());
if (rv == ERR_IO_PENDING)
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(0u, transport_pool->IdleSocketCountInGroup(kSocketGroup));
EXPECT_EQ(HttpAuthHandlerMock::State::WAIT_FOR_GENERATE_AUTH_TOKEN,
auth_handler->state());
// Fourth round of authentication, which completes successfully.
auth_handler->SetGenerateExpectation(false, OK);
rv = trans.RestartWithAuth(AuthCredentials(), callback.callback());
if (rv == ERR_IO_PENDING)
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_FALSE(response->auth_challenge.has_value());
EXPECT_EQ(0u, transport_pool->IdleSocketCountInGroup(kSocketGroup));
// In WAIT_FOR_CHALLENGE, although in reality the auth handler is done. A real
// auth handler should transition to a DONE state in concert with the remote
// server. But that's not something we can test here with a mock handler.
EXPECT_EQ(HttpAuthHandlerMock::State::WAIT_FOR_CHALLENGE,
auth_handler->state());
// Read the body since the fourth round was successful. This will also
// release the socket back to the pool.
scoped_refptr<IOBufferWithSize> io_buf =
base::MakeRefCounted<IOBufferWithSize>(50);
rv = trans.Read(io_buf.get(), io_buf->size(), callback.callback());
if (rv == ERR_IO_PENDING)
rv = callback.WaitForResult();
EXPECT_EQ(3, rv);
rv = trans.Read(io_buf.get(), io_buf->size(), callback.callback());
EXPECT_EQ(0, rv);
// There are still 0 idle sockets, since the trans_compete transaction
// will be handed it immediately after trans releases it to the group.
EXPECT_EQ(0u, transport_pool->IdleSocketCountInGroup(kSocketGroup));
// The competing request can now finish. Wait for the headers and then
// read the body.
rv = callback_compete.WaitForResult();
EXPECT_THAT(rv, IsOk());
rv = trans_compete.Read(io_buf.get(), io_buf->size(), callback.callback());
if (rv == ERR_IO_PENDING)
rv = callback.WaitForResult();
EXPECT_EQ(3, rv);
rv = trans_compete.Read(io_buf.get(), io_buf->size(), callback.callback());
EXPECT_EQ(0, rv);
// Finally, the socket is released to the group.
EXPECT_EQ(1u, transport_pool->IdleSocketCountInGroup(kSocketGroup));
}
// This tests the case that a request is issued via http instead of spdy after
// npn is negotiated.
TEST_F(HttpNetworkTransactionTest, NpnWithHttpOverSSL) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead(kAlternativeServiceHttpHeader),
MockRead("\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP11;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
EXPECT_FALSE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
}
// Simulate the SSL handshake completing with an NPN negotiation followed by an
// immediate server closing of the socket.
// Regression test for https://crbug.com/46369.
TEST_F(HttpNetworkTransactionTest, SpdyPostNPNServerHangup) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
spdy::SpdySerializedFrame req(
spdy_util_.ConstructSpdyGet(nullptr, 0, 1, LOWEST));
MockWrite spdy_writes[] = {CreateMockWrite(req, 1)};
MockRead spdy_reads[] = {
MockRead(SYNCHRONOUS, 0, 0) // Not async - return 0 immediately.
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
TestCompletionCallback callback;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsError(ERR_CONNECTION_CLOSED));
}
// A subclass of HttpAuthHandlerMock that records the request URL when
// it gets it. This is needed since the auth handler may get destroyed
// before we get a chance to query it.
class UrlRecordingHttpAuthHandlerMock : public HttpAuthHandlerMock {
public:
explicit UrlRecordingHttpAuthHandlerMock(GURL* url) : url_(url) {}
~UrlRecordingHttpAuthHandlerMock() override = default;
protected:
int GenerateAuthTokenImpl(const AuthCredentials* credentials,
const HttpRequestInfo* request,
CompletionOnceCallback callback,
std::string* auth_token) override {
*url_ = request->url;
return HttpAuthHandlerMock::GenerateAuthTokenImpl(
credentials, request, std::move(callback), auth_token);
}
private:
GURL* url_;
};
// Test that if we cancel the transaction as the connection is completing, that
// everything tears down correctly.
TEST_F(HttpNetworkTransactionTest, SimpleCancel) {
// Setup everything about the connection to complete synchronously, so that
// after calling HttpNetworkTransaction::Start, the only thing we're waiting
// for is the callback from the HttpStreamRequest.
// Then cancel the transaction.
// Verify that we don't crash.
MockConnect mock_connect(SYNCHRONOUS, OK);
MockRead data_reads[] = {
MockRead(SYNCHRONOUS, "HTTP/1.0 200 OK\r\n\r\n"),
MockRead(SYNCHRONOUS, "hello world"),
MockRead(SYNCHRONOUS, OK),
};
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
data.set_connect_data(mock_connect);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
BoundTestNetLog log;
int rv = trans->Start(&request, callback.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
trans.reset(); // Cancel the transaction here.
base::RunLoop().RunUntilIdle();
}
// Test that if a transaction is cancelled after receiving the headers, the
// stream is drained properly and added back to the socket pool. The main
// purpose of this test is to make sure that an HttpStreamParser can be read
// from after the HttpNetworkTransaction and the objects it owns have been
// deleted.
// See http://crbug.com/368418
TEST_F(HttpNetworkTransactionTest, CancelAfterHeaders) {
MockRead data_reads[] = {
MockRead(ASYNC, "HTTP/1.1 200 OK\r\n"),
MockRead(ASYNC, "Content-Length: 2\r\n"),
MockRead(ASYNC, "Connection: Keep-Alive\r\n\r\n"),
MockRead(ASYNC, "1"),
// 2 async reads are necessary to trigger a ReadResponseBody call after the
// HttpNetworkTransaction has been deleted.
MockRead(ASYNC, "2"),
MockRead(SYNCHRONOUS, ERR_IO_PENDING), // Should never read this.
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
{
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
callback.WaitForResult();
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
// The transaction and HttpRequestInfo are deleted.
}
// Let the HttpResponseBodyDrainer drain the socket.
base::RunLoop().RunUntilIdle();
// Socket should now be idle, waiting to be reused.
EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
}
// Test a basic GET request through a proxy.
TEST_F(HttpNetworkTransactionTest, ProxyGet) {
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes1[] = {
MockWrite(
"GET http://www.example.org/ HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
BeforeHeadersSentHandler headers_handler;
trans.SetBeforeHeadersSentCallback(
base::Bind(&BeforeHeadersSentHandler::OnBeforeHeadersSent,
base::Unretained(&headers_handler)));
int rv = trans.Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(100, response->headers->GetContentLength());
EXPECT_TRUE(response->was_fetched_via_proxy);
EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
HostPortPair::FromString("myproxy:70")),
response->proxy_server);
EXPECT_TRUE(headers_handler.observed_before_headers_sent());
EXPECT_TRUE(headers_handler.observed_before_headers_sent_with_proxy());
EXPECT_EQ("myproxy:70", headers_handler.observed_proxy_server_uri());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReusedWithPac(load_timing_info,
CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
}
// Test a basic HTTPS GET request through a proxy.
TEST_F(HttpNetworkTransactionTest, ProxyTunnelGet) {
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
BeforeHeadersSentHandler headers_handler;
trans.SetBeforeHeadersSentCallback(
base::Bind(&BeforeHeadersSentHandler::OnBeforeHeadersSent,
base::Unretained(&headers_handler)));
int rv = trans.Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
TestNetLogEntry::List entries;
log.GetEntries(&entries);
size_t pos = ExpectLogContainsSomewhere(
entries, 0, NetLogEventType::HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
NetLogEventPhase::NONE);
ExpectLogContainsSomewhere(
entries, pos,
NetLogEventType::HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
NetLogEventPhase::NONE);
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(100, response->headers->GetContentLength());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
EXPECT_TRUE(response->was_fetched_via_proxy);
EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
HostPortPair::FromString("myproxy:70")),
response->proxy_server);
EXPECT_TRUE(headers_handler.observed_before_headers_sent());
EXPECT_TRUE(headers_handler.observed_before_headers_sent_with_proxy());
EXPECT_EQ("myproxy:70", headers_handler.observed_proxy_server_uri());
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReusedWithPac(load_timing_info,
CONNECT_TIMING_HAS_SSL_TIMES);
}
// Test a basic HTTPS GET request through a proxy, connecting to an IPv6
// literal host.
TEST_F(HttpNetworkTransactionTest, ProxyTunnelGetIPv6) {
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://[::2]:443/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite("CONNECT [::2]:443 HTTP/1.1\r\n"
"Host: [::2]:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: [::2]\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
TestNetLogEntry::List entries;
log.GetEntries(&entries);
size_t pos = ExpectLogContainsSomewhere(
entries, 0, NetLogEventType::HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
NetLogEventPhase::NONE);
ExpectLogContainsSomewhere(
entries, pos,
NetLogEventType::HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
NetLogEventPhase::NONE);
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers->IsKeepAlive());
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(100, response->headers->GetContentLength());
EXPECT_TRUE(HttpVersion(1, 1) == response->headers->GetHttpVersion());
EXPECT_TRUE(response->was_fetched_via_proxy);
EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
HostPortPair::FromString("myproxy:70")),
response->proxy_server);
LoadTimingInfo load_timing_info;
EXPECT_TRUE(trans.GetLoadTimingInfo(&load_timing_info));
TestLoadTimingNotReusedWithPac(load_timing_info,
CONNECT_TIMING_HAS_SSL_TIMES);
}
// Test a basic HTTPS GET request through a proxy, but the server hangs up
// while establishing the tunnel.
TEST_F(HttpNetworkTransactionTest, ProxyTunnelGetHangup) {
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
MockRead(ASYNC, 0, 0), // EOF
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_EMPTY_RESPONSE));
TestNetLogEntry::List entries;
log.GetEntries(&entries);
size_t pos = ExpectLogContainsSomewhere(
entries, 0, NetLogEventType::HTTP_TRANSACTION_SEND_TUNNEL_HEADERS,
NetLogEventPhase::NONE);
ExpectLogContainsSomewhere(
entries, pos,
NetLogEventType::HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS,
NetLogEventPhase::NONE);
}
// Test for crbug.com/55424.
TEST_F(HttpNetworkTransactionTest, PreconnectWithExistingSpdySession) {
spdy::SpdySerializedFrame req(
spdy_util_.ConstructSpdyGet("https://www.example.org", 1, LOWEST));
MockWrite spdy_writes[] = {CreateMockWrite(req, 0)};
spdy::SpdySerializedFrame resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame data(spdy_util_.ConstructSpdyDataFrame(1, true));
MockRead spdy_reads[] = {
CreateMockRead(resp, 1), CreateMockRead(data, 2), MockRead(ASYNC, 0, 3),
};
SequencedSocketData spdy_data(spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Set up an initial SpdySession in the pool to reuse.
HostPortPair host_port_pair("www.example.org", 443);
SpdySessionKey key(host_port_pair, ProxyServer::Direct(),
PRIVACY_MODE_DISABLED,
SpdySessionKey::IsProxySession::kFalse, SocketTag());
base::WeakPtr<SpdySession> spdy_session =
CreateSpdySession(session.get(), key, NetLogWithSource());
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
}
// Given a net error, cause that error to be returned from the first Write()
// call and verify that the HttpNetworkTransaction fails with that error.
void HttpNetworkTransactionTest::CheckErrorIsPassedBack(
int error, IoMode mode) {
HttpRequestInfo request_info;
request_info.url = GURL("https://www.example.com/");
request_info.method = "GET";
request_info.load_flags = LOAD_NORMAL;
request_info.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
SSLSocketDataProvider ssl_data(mode, OK);
MockWrite data_writes[] = {
MockWrite(mode, error),
};
StaticSocketDataProvider data(base::span<MockRead>(), data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&request_info, callback.callback(), NetLogWithSource());
if (rv == ERR_IO_PENDING)
rv = callback.WaitForResult();
ASSERT_EQ(error, rv);
}
TEST_F(HttpNetworkTransactionTest, SSLWriteCertError) {
// Just check a grab bag of cert errors.
static const int kErrors[] = {
ERR_CERT_COMMON_NAME_INVALID,
ERR_CERT_AUTHORITY_INVALID,
ERR_CERT_DATE_INVALID,
};
for (size_t i = 0; i < base::size(kErrors); i++) {
CheckErrorIsPassedBack(kErrors[i], ASYNC);
CheckErrorIsPassedBack(kErrors[i], SYNCHRONOUS);
}
}
// Ensure that a client certificate is removed from the SSL client auth
// cache when:
// 1) No proxy is involved.
// 2) TLS False Start is disabled.
// 3) The initial TLS handshake requests a client certificate.
// 4) The client supplies an invalid/unacceptable certificate.
TEST_F(HttpNetworkTransactionTest, ClientAuthCertCache_Direct_NoFalseStart) {
HttpRequestInfo request_info;
request_info.url = GURL("https://www.example.com/");
request_info.method = "GET";
request_info.load_flags = LOAD_NORMAL;
request_info.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
scoped_refptr<SSLCertRequestInfo> cert_request(new SSLCertRequestInfo());
cert_request->host_and_port = HostPortPair("www.example.com", 443);
// [ssl_]data1 contains the data for the first SSL handshake. When a
// CertificateRequest is received for the first time, the handshake will
// be aborted to allow the caller to provide a certificate.
SSLSocketDataProvider ssl_data1(ASYNC, ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
ssl_data1.cert_request_info = cert_request.get();
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data1);
StaticSocketDataProvider data1;
session_deps_.socket_factory->AddSocketDataProvider(&data1);
// [ssl_]data2 contains the data for the second SSL handshake. When TLS
// False Start is not being used, the result of the SSL handshake will be
// returned as part of the SSLClientSocket::Connect() call. This test
// matches the result of a server sending a handshake_failure alert,
// rather than a Finished message, because it requires a client
// certificate and none was supplied.
SSLSocketDataProvider ssl_data2(ASYNC, ERR_SSL_PROTOCOL_ERROR);
ssl_data2.cert_request_info = cert_request.get();
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data2);
StaticSocketDataProvider data2;
session_deps_.socket_factory->AddSocketDataProvider(&data2);
// [ssl_]data3 contains the data for the third SSL handshake. When a
// connection to a server fails during an SSL handshake,
// HttpNetworkTransaction will attempt to fallback to TLSv1.2 if the previous
// connection was attempted with TLSv1.3. This is transparent to the caller
// of the HttpNetworkTransaction. Because this test failure is due to
// requiring a client certificate, this fallback handshake should also
// fail.
SSLSocketDataProvider ssl_data3(ASYNC, ERR_SSL_PROTOCOL_ERROR);
ssl_data3.expected_ssl_version_max = SSL_PROTOCOL_VERSION_TLS1_2;
ssl_data3.cert_request_info = cert_request.get();
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data3);
StaticSocketDataProvider data3;
session_deps_.socket_factory->AddSocketDataProvider(&data3);
// [ssl_]data4 contains the data for the fourth SSL handshake. When a
// connection to a server fails during an SSL handshake,
// HttpNetworkTransaction will attempt to fallback to TLSv1 if the previous
// connection was attempted with TLSv1.1. This is transparent to the caller
// of the HttpNetworkTransaction. Because this test failure is due to
// requiring a client certificate, this fallback handshake should also
// fail.
SSLSocketDataProvider ssl_data4(ASYNC, ERR_SSL_PROTOCOL_ERROR);
ssl_data4.cert_request_info = cert_request.get();
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data4);
StaticSocketDataProvider data4;
session_deps_.socket_factory->AddSocketDataProvider(&data4);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Begin the SSL handshake with the peer. This consumes ssl_data1.
TestCompletionCallback callback;
int rv = trans.Start(&request_info, callback.callback(), NetLogWithSource());
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
// Complete the SSL handshake, which should abort due to requiring a
// client certificate.
rv = callback.WaitForResult();
ASSERT_THAT(rv, IsError(ERR_SSL_CLIENT_AUTH_CERT_NEEDED));
// Indicate that no certificate should be supplied. From the perspective
// of SSLClientCertCache, NULL is just as meaningful as a real
// certificate, so this is the same as supply a
// legitimate-but-unacceptable certificate.
rv = trans.RestartWithCertificate(nullptr, nullptr, callback.callback());
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
// Ensure the certificate was added to the client auth cache before
// allowing the connection to continue restarting.
scoped_refptr<X509Certificate> client_cert;
scoped_refptr<SSLPrivateKey> client_private_key;
ASSERT_TRUE(session->ssl_client_auth_cache()->Lookup(
HostPortPair("www.example.com", 443), &client_cert, &client_private_key));
ASSERT_FALSE(client_cert);
// Restart the handshake. This will consume ssl_data2, which fails, and
// then consume ssl_data3 and ssl_data4, both of which should also fail.
// The result code is checked against what ssl_data4 should return.
rv = callback.WaitForResult();
ASSERT_THAT(rv, IsError(ERR_SSL_PROTOCOL_ERROR));
// Ensure that the client certificate is removed from the cache on a
// handshake failure.
ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
HostPortPair("www.example.com", 443), &client_cert, &client_private_key));
}
// Ensure that a client certificate is removed from the SSL client auth
// cache when:
// 1) No proxy is involved.
// 2) TLS False Start is enabled.
// 3) The initial TLS handshake requests a client certificate.
// 4) The client supplies an invalid/unacceptable certificate.
TEST_F(HttpNetworkTransactionTest, ClientAuthCertCache_Direct_FalseStart) {
HttpRequestInfo request_info;
request_info.url = GURL("https://www.example.com/");
request_info.method = "GET";
request_info.load_flags = LOAD_NORMAL;
request_info.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
scoped_refptr<SSLCertRequestInfo> cert_request(new SSLCertRequestInfo());
cert_request->host_and_port = HostPortPair("www.example.com", 443);
// When TLS False Start is used, SSLClientSocket::Connect() calls will
// return successfully after reading up to the peer's Certificate message.
// This is to allow the caller to call SSLClientSocket::Write(), which can
// enqueue application data to be sent in the same packet as the
// ChangeCipherSpec and Finished messages.
// The actual handshake will be finished when SSLClientSocket::Read() is
// called, which expects to process the peer's ChangeCipherSpec and
// Finished messages. If there was an error negotiating with the peer,
// such as due to the peer requiring a client certificate when none was
// supplied, the alert sent by the peer won't be processed until Read() is
// called.
// Like the non-False Start case, when a client certificate is requested by
// the peer, the handshake is aborted during the Connect() call.
// [ssl_]data1 represents the initial SSL handshake with the peer.
SSLSocketDataProvider ssl_data1(ASYNC, ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
ssl_data1.cert_request_info = cert_request.get();
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data1);
StaticSocketDataProvider data1;
session_deps_.socket_factory->AddSocketDataProvider(&data1);
// When a client certificate is supplied, Connect() will not be aborted
// when the peer requests the certificate. Instead, the handshake will
// artificially succeed, allowing the caller to write the HTTP request to
// the socket. The handshake messages are not processed until Read() is
// called, which then detects that the handshake was aborted, due to the
// peer sending a handshake_failure because it requires a client
// certificate.
SSLSocketDataProvider ssl_data2(ASYNC, OK);
ssl_data2.cert_request_info = cert_request.get();
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data2);
MockRead data2_reads[] = {
MockRead(ASYNC /* async */, ERR_SSL_PROTOCOL_ERROR),
};
StaticSocketDataProvider data2(data2_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data2);
// As described in ClientAuthCertCache_Direct_NoFalseStart, [ssl_]data3 is
// the data for the SSL handshake once the TLSv1.1 connection falls back to
// TLSv1. It has the same behaviour as [ssl_]data2.
SSLSocketDataProvider ssl_data3(ASYNC, OK);
ssl_data3.cert_request_info = cert_request.get();
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data3);
StaticSocketDataProvider data3(data2_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data3);
// [ssl_]data4 is the data for the SSL handshake once the TLSv1 connection
// falls back to SSLv3. It has the same behaviour as [ssl_]data2.
SSLSocketDataProvider ssl_data4(ASYNC, OK);
ssl_data4.cert_request_info = cert_request.get();
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data4);
StaticSocketDataProvider data4(data2_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data4);
// Need one more if TLSv1.2 is enabled.
SSLSocketDataProvider ssl_data5(ASYNC, OK);
ssl_data5.cert_request_info = cert_request.get();
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data5);
StaticSocketDataProvider data5(data2_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data5);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Begin the initial SSL handshake.
TestCompletionCallback callback;
int rv = trans.Start(&request_info, callback.callback(), NetLogWithSource());
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
// Complete the SSL handshake, which should abort due to requiring a
// client certificate.
rv = callback.WaitForResult();
ASSERT_THAT(rv, IsError(ERR_SSL_CLIENT_AUTH_CERT_NEEDED));
// Indicate that no certificate should be supplied. From the perspective
// of SSLClientCertCache, NULL is just as meaningful as a real
// certificate, so this is the same as supply a
// legitimate-but-unacceptable certificate.
rv = trans.RestartWithCertificate(nullptr, nullptr, callback.callback());
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
// Ensure the certificate was added to the client auth cache before
// allowing the connection to continue restarting.
scoped_refptr<X509Certificate> client_cert;
scoped_refptr<SSLPrivateKey> client_private_key;
ASSERT_TRUE(session->ssl_client_auth_cache()->Lookup(
HostPortPair("www.example.com", 443), &client_cert, &client_private_key));
ASSERT_FALSE(client_cert);
// Restart the handshake. This will consume ssl_data2, which fails, and
// then consume ssl_data3 and ssl_data4, both of which should also fail.
// The result code is checked against what ssl_data4 should return.
rv = callback.WaitForResult();
ASSERT_THAT(rv, IsError(ERR_SSL_PROTOCOL_ERROR));
// Ensure that the client certificate is removed from the cache on a
// handshake failure.
ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
HostPortPair("www.example.com", 443), &client_cert, &client_private_key));
}
// Ensure that a client certificate is removed from the SSL client auth
// cache when:
// 1) An HTTPS proxy is involved.
// 3) The HTTPS proxy requests a client certificate.
// 4) The client supplies an invalid/unacceptable certificate for the
// proxy.
TEST_F(HttpNetworkTransactionTest, ClientAuthCertCache_Proxy_Fail) {
session_deps_.proxy_resolution_service = ProxyResolutionService::CreateFixed(
"https://proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
auto cert_request = base::MakeRefCounted<SSLCertRequestInfo>();
cert_request->host_and_port = HostPortPair("proxy", 70);
// Repeat the test for connecting to an HTTPS endpoint, then for connecting to
// an HTTP endpoint.
HttpRequestInfo requests[2];
requests[0].url = GURL("https://www.example.com/");
requests[0].method = "GET";
requests[0].load_flags = LOAD_NORMAL;
requests[0].traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// HTTPS requests are tunneled.
MockWrite https_writes[] = {
MockWrite("CONNECT www.example.com:443 HTTP/1.1\r\n"
"Host: www.example.com:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
requests[1].url = GURL("http://www.example.com/");
requests[1].method = "GET";
requests[1].load_flags = LOAD_NORMAL;
requests[1].traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// HTTP requests are not.
MockWrite http_writes[] = {
MockWrite("GET http://www.example.com/ HTTP/1.1\r\n"
"Host: www.example.com\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
// When the server rejects the client certificate, it will close the
// connection. In TLS 1.2, this is signaled out of Connect(). In TLS 1.3 (or
// TLS 1.2 with False Start), the error is returned out of the first Read().
for (bool reject_in_connect : {true, false}) {
SCOPED_TRACE(reject_in_connect);
// Client certificate errors are typically signaled with
// ERR_BAD_SSL_CLIENT_AUTH_CERT, but sometimes the server gives an arbitrary
// protocol error.
for (Error reject_error :
{ERR_SSL_PROTOCOL_ERROR, ERR_BAD_SSL_CLIENT_AUTH_CERT}) {
SCOPED_TRACE(reject_error);
// Tunneled and non-tunneled requests are handled differently. Test both.
for (const HttpRequestInfo& request : requests) {
SCOPED_TRACE(request.url);
session_deps_.socket_factory =
std::make_unique<MockClientSocketFactory>();
// See ClientAuthCertCache_Direct_NoFalseStart for the explanation of
// [ssl_]data[1-2]. [ssl_]data3 is not needed because we do not retry
// for proxies. Rather than represending the endpoint
// (www.example.com:443), they represent failures with the HTTPS proxy
// (proxy:70).
SSLSocketDataProvider ssl_data1(ASYNC, ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
ssl_data1.cert_request_info = cert_request.get();
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl_data1);
StaticSocketDataProvider data1;
session_deps_.socket_factory->AddSocketDataProvider(&data1);
base::Optional<SSLSocketDataProvider> ssl_data2;
base::Optional<StaticSocketDataProvider> data2;
MockRead error_in_read[] = {MockRead(ASYNC, reject_error)};
if (reject_in_connect) {
ssl_data2.emplace(ASYNC, reject_error);
// There are no reads or writes.
data2.emplace();
} else {
ssl_data2.emplace(ASYNC, OK);
// We will get one Write() in before observing the error in Read().
if (request.url.SchemeIsCryptographic()) {
data2.emplace(error_in_read, https_writes);
} else {
data2.emplace(error_in_read, http_writes);
}
}
ssl_data2->cert_request_info = cert_request.get();
session_deps_.socket_factory->AddSSLSocketDataProvider(
&ssl_data2.value());
session_deps_.socket_factory->AddSocketDataProvider(&data2.value());
std::unique_ptr<HttpNetworkSession> session =
CreateSession(&session_deps_);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Begin the SSL handshake with the proxy.
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
// Complete the SSL handshake, which should abort due to requiring a
// client certificate.
rv = callback.WaitForResult();
ASSERT_THAT(rv, IsError(ERR_SSL_CLIENT_AUTH_CERT_NEEDED));
// Indicate that no certificate should be supplied. From the
// perspective of SSLClientCertCache, NULL is just as meaningful as a
// real certificate, so this is the same as supply a
// legitimate-but-unacceptable certificate.
rv =
trans.RestartWithCertificate(nullptr, nullptr, callback.callback());
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
// Ensure the certificate was added to the client auth cache before
// allowing the connection to continue restarting.
scoped_refptr<X509Certificate> client_cert;
scoped_refptr<SSLPrivateKey> client_private_key;
ASSERT_TRUE(session->ssl_client_auth_cache()->Lookup(
HostPortPair("proxy", 70), &client_cert, &client_private_key));
ASSERT_FALSE(client_cert);
// Ensure the certificate was NOT cached for the endpoint. This only
// applies to HTTPS requests, but is fine to check for HTTP requests.
ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
HostPortPair("www.example.com", 443), &client_cert,
&client_private_key));
// Restart the handshake. This will consume ssl_data2. The result code
// is checked against what ssl_data2 should return.
rv = callback.WaitForResult();
ASSERT_THAT(rv, AnyOf(IsError(ERR_PROXY_CONNECTION_FAILED),
IsError(reject_error)));
// Now that the new handshake has failed, ensure that the client
// certificate was removed from the client auth cache.
ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
HostPortPair("proxy", 70), &client_cert, &client_private_key));
ASSERT_FALSE(session->ssl_client_auth_cache()->Lookup(
HostPortPair("www.example.com", 443), &client_cert,
&client_private_key));
}
}
}
}
TEST_F(HttpNetworkTransactionTest, UseIPConnectionPooling) {
// Set up a special HttpNetworkSession with a MockCachingHostResolver.
session_deps_.host_resolver = std::make_unique<MockCachingHostResolver>();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
AddSSLSocketData();
spdy::SpdySerializedFrame host1_req(
spdy_util_.ConstructSpdyGet("https://www.example.org", 1, LOWEST));
spdy_util_.UpdateWithStreamDestruction(1);
spdy::SpdySerializedFrame host2_req(
spdy_util_.ConstructSpdyGet("https://mail.example.com", 3, LOWEST));
MockWrite spdy_writes[] = {
CreateMockWrite(host1_req, 0), CreateMockWrite(host2_req, 3),
};
spdy::SpdySerializedFrame host1_resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame host1_resp_body(
spdy_util_.ConstructSpdyDataFrame(1, true));
spdy::SpdySerializedFrame host2_resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 3));
spdy::SpdySerializedFrame host2_resp_body(
spdy_util_.ConstructSpdyDataFrame(3, true));
MockRead spdy_reads[] = {
CreateMockRead(host1_resp, 1), CreateMockRead(host1_resp_body, 2),
CreateMockRead(host2_resp, 4), CreateMockRead(host2_resp_body, 5),
MockRead(ASYNC, 0, 6),
};
IPEndPoint peer_addr(IPAddress::IPv4Localhost(), 443);
MockConnect connect(ASYNC, OK, peer_addr);
SequencedSocketData spdy_data(connect, spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
TestCompletionCallback callback;
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("https://www.example.org/");
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
int rv = trans1.Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans1.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans1, &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
// Preload mail.example.com into HostCache.
rv = session_deps_.host_resolver->LoadIntoCache(
HostPortPair("mail.example.com", 443), base::nullopt);
EXPECT_THAT(rv, IsOk());
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("https://mail.example.com/");
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
rv = trans2.Start(&request2, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
response = trans2.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
ASSERT_THAT(ReadTransaction(&trans2, &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
}
TEST_F(HttpNetworkTransactionTest, UseIPConnectionPoolingAfterResolution) {
// Set up a special HttpNetworkSession with a MockCachingHostResolver.
session_deps_.host_resolver = std::make_unique<MockCachingHostResolver>();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
AddSSLSocketData();
spdy::SpdySerializedFrame host1_req(
spdy_util_.ConstructSpdyGet("https://www.example.org", 1, LOWEST));
spdy_util_.UpdateWithStreamDestruction(1);
spdy::SpdySerializedFrame host2_req(
spdy_util_.ConstructSpdyGet("https://mail.example.com", 3, LOWEST));
MockWrite spdy_writes[] = {
CreateMockWrite(host1_req, 0), CreateMockWrite(host2_req, 3),
};
spdy::SpdySerializedFrame host1_resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame host1_resp_body(
spdy_util_.ConstructSpdyDataFrame(1, true));
spdy::SpdySerializedFrame host2_resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 3));
spdy::SpdySerializedFrame host2_resp_body(
spdy_util_.ConstructSpdyDataFrame(3, true));
MockRead spdy_reads[] = {
CreateMockRead(host1_resp, 1), CreateMockRead(host1_resp_body, 2),
CreateMockRead(host2_resp, 4), CreateMockRead(host2_resp_body, 5),
MockRead(ASYNC, 0, 6),
};
IPEndPoint peer_addr(IPAddress::IPv4Localhost(), 443);
MockConnect connect(ASYNC, OK, peer_addr);
SequencedSocketData spdy_data(connect, spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
TestCompletionCallback callback;
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("https://www.example.org/");
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
int rv = trans1.Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans1.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans1, &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("https://mail.example.com/");
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
rv = trans2.Start(&request2, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
response = trans2.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
ASSERT_THAT(ReadTransaction(&trans2, &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
}
// Regression test for https://crbug.com/546991.
// The server might not be able to serve an IP pooled request, and might send a
// 421 Misdirected Request response status to indicate this.
// HttpNetworkTransaction should reset the request and retry without IP pooling.
TEST_F(HttpNetworkTransactionTest, RetryWithoutConnectionPooling) {
// Two hosts resolve to the same IP address.
const std::string ip_addr = "1.2.3.4";
IPAddress ip;
ASSERT_TRUE(ip.AssignFromIPLiteral(ip_addr));
IPEndPoint peer_addr = IPEndPoint(ip, 443);
session_deps_.host_resolver = std::make_unique<MockCachingHostResolver>();
session_deps_.host_resolver->rules()->AddRule("www.example.org", ip_addr);
session_deps_.host_resolver->rules()->AddRule("mail.example.org", ip_addr);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Two requests on the first connection.
spdy::SpdySerializedFrame req1(
spdy_util_.ConstructSpdyGet("https://www.example.org", 1, LOWEST));
spdy_util_.UpdateWithStreamDestruction(1);
spdy::SpdySerializedFrame req2(
spdy_util_.ConstructSpdyGet("https://mail.example.org", 3, LOWEST));
spdy::SpdySerializedFrame rst(
spdy_util_.ConstructSpdyRstStream(3, spdy::ERROR_CODE_CANCEL));
MockWrite writes1[] = {
CreateMockWrite(req1, 0), CreateMockWrite(req2, 3),
CreateMockWrite(rst, 6),
};
// The first one succeeds, the second gets error 421 Misdirected Request.
spdy::SpdySerializedFrame resp1(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame body1(spdy_util_.ConstructSpdyDataFrame(1, true));
spdy::SpdyHeaderBlock response_headers;
response_headers[spdy::kHttp2StatusHeader] = "421";
spdy::SpdySerializedFrame resp2(
spdy_util_.ConstructSpdyReply(3, std::move(response_headers)));
MockRead reads1[] = {CreateMockRead(resp1, 1), CreateMockRead(body1, 2),
CreateMockRead(resp2, 4), MockRead(ASYNC, 0, 5)};
MockConnect connect1(ASYNC, OK, peer_addr);
SequencedSocketData data1(connect1, reads1, writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
AddSSLSocketData();
// Retry the second request on a second connection.
SpdyTestUtil spdy_util2;
spdy::SpdySerializedFrame req3(
spdy_util2.ConstructSpdyGet("https://mail.example.org", 1, LOWEST));
MockWrite writes2[] = {
CreateMockWrite(req3, 0),
};
spdy::SpdySerializedFrame resp3(
spdy_util2.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame body3(spdy_util2.ConstructSpdyDataFrame(1, true));
MockRead reads2[] = {CreateMockRead(resp3, 1), CreateMockRead(body3, 2),
MockRead(ASYNC, 0, 3)};
MockConnect connect2(ASYNC, OK, peer_addr);
SequencedSocketData data2(connect2, reads2, writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
AddSSLSocketData();
// Preload mail.example.org into HostCache.
int rv = session_deps_.host_resolver->LoadIntoCache(
HostPortPair("mail.example.com", 443), base::nullopt);
EXPECT_THAT(rv, IsOk());
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("https://www.example.org/");
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
rv = trans1.Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans1.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans1, &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("https://mail.example.org/");
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
BoundTestNetLog log;
rv = trans2.Start(&request2, callback.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
response = trans2.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
ASSERT_THAT(ReadTransaction(&trans2, &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
TestNetLogEntry::List entries;
log.GetEntries(&entries);
ExpectLogContainsSomewhere(
entries, 0, NetLogEventType::HTTP_TRANSACTION_RESTART_MISDIRECTED_REQUEST,
NetLogEventPhase::NONE);
}
// Test that HTTP 421 responses are properly returned to the caller if received
// on the retry as well. HttpNetworkTransaction should not infinite loop or lose
// portions of the response.
TEST_F(HttpNetworkTransactionTest, ReturnHTTP421OnRetry) {
// Two hosts resolve to the same IP address.
const std::string ip_addr = "1.2.3.4";
IPAddress ip;
ASSERT_TRUE(ip.AssignFromIPLiteral(ip_addr));
IPEndPoint peer_addr = IPEndPoint(ip, 443);
session_deps_.host_resolver = std::make_unique<MockCachingHostResolver>();
session_deps_.host_resolver->rules()->AddRule("www.example.org", ip_addr);
session_deps_.host_resolver->rules()->AddRule("mail.example.org", ip_addr);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Two requests on the first connection.
spdy::SpdySerializedFrame req1(
spdy_util_.ConstructSpdyGet("https://www.example.org", 1, LOWEST));
spdy_util_.UpdateWithStreamDestruction(1);
spdy::SpdySerializedFrame req2(
spdy_util_.ConstructSpdyGet("https://mail.example.org", 3, LOWEST));
spdy::SpdySerializedFrame rst(
spdy_util_.ConstructSpdyRstStream(3, spdy::ERROR_CODE_CANCEL));
MockWrite writes1[] = {
CreateMockWrite(req1, 0), CreateMockWrite(req2, 3),
CreateMockWrite(rst, 6),
};
// The first one succeeds, the second gets error 421 Misdirected Request.
spdy::SpdySerializedFrame resp1(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame body1(spdy_util_.ConstructSpdyDataFrame(1, true));
spdy::SpdyHeaderBlock response_headers;
response_headers[spdy::kHttp2StatusHeader] = "421";
spdy::SpdySerializedFrame resp2(
spdy_util_.ConstructSpdyReply(3, response_headers.Clone()));
MockRead reads1[] = {CreateMockRead(resp1, 1), CreateMockRead(body1, 2),
CreateMockRead(resp2, 4), MockRead(ASYNC, 0, 5)};
MockConnect connect1(ASYNC, OK, peer_addr);
SequencedSocketData data1(connect1, reads1, writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
AddSSLSocketData();
// Retry the second request on a second connection. It returns 421 Misdirected
// Retry again.
SpdyTestUtil spdy_util2;
spdy::SpdySerializedFrame req3(
spdy_util2.ConstructSpdyGet("https://mail.example.org", 1, LOWEST));
MockWrite writes2[] = {
CreateMockWrite(req3, 0),
};
spdy::SpdySerializedFrame resp3(
spdy_util2.ConstructSpdyReply(1, std::move(response_headers)));
spdy::SpdySerializedFrame body3(spdy_util2.ConstructSpdyDataFrame(1, true));
MockRead reads2[] = {CreateMockRead(resp3, 1), CreateMockRead(body3, 2),
MockRead(ASYNC, 0, 3)};
MockConnect connect2(ASYNC, OK, peer_addr);
SequencedSocketData data2(connect2, reads2, writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
AddSSLSocketData();
// Preload mail.example.org into HostCache.
int rv = session_deps_.host_resolver->LoadIntoCache(
HostPortPair("mail.example.com", 443), base::nullopt);
EXPECT_THAT(rv, IsOk());
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("https://www.example.org/");
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
rv = trans1.Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans1.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans1, &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("https://mail.example.org/");
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
BoundTestNetLog log;
rv = trans2.Start(&request2, callback.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
// After a retry, the 421 Misdirected Request is reported back up to the
// caller.
response = trans2.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 421", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
EXPECT_TRUE(response->ssl_info.cert);
ASSERT_THAT(ReadTransaction(&trans2, &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
}
TEST_F(HttpNetworkTransactionTest,
UseIPConnectionPoolingWithHostCacheExpiration) {
// Set up HostResolver to invalidate cached entries after 1 cached resolve.
session_deps_.host_resolver =
std::make_unique<MockCachingHostResolver>(1 /* cache_invalidation_num */);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
AddSSLSocketData();
spdy::SpdySerializedFrame host1_req(
spdy_util_.ConstructSpdyGet("https://www.example.org", 1, LOWEST));
spdy_util_.UpdateWithStreamDestruction(1);
spdy::SpdySerializedFrame host2_req(
spdy_util_.ConstructSpdyGet("https://mail.example.com", 3, LOWEST));
MockWrite spdy_writes[] = {
CreateMockWrite(host1_req, 0), CreateMockWrite(host2_req, 3),
};
spdy::SpdySerializedFrame host1_resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame host1_resp_body(
spdy_util_.ConstructSpdyDataFrame(1, true));
spdy::SpdySerializedFrame host2_resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 3));
spdy::SpdySerializedFrame host2_resp_body(
spdy_util_.ConstructSpdyDataFrame(3, true));
MockRead spdy_reads[] = {
CreateMockRead(host1_resp, 1), CreateMockRead(host1_resp_body, 2),
CreateMockRead(host2_resp, 4), CreateMockRead(host2_resp_body, 5),
MockRead(ASYNC, 0, 6),
};
IPEndPoint peer_addr(IPAddress::IPv4Localhost(), 443);
MockConnect connect(ASYNC, OK, peer_addr);
SequencedSocketData spdy_data(connect, spdy_reads, spdy_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy_data);
TestCompletionCallback callback;
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("https://www.example.org/");
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
int rv = trans1.Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans1.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans1, &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
// Preload cache entries into HostCache.
rv = session_deps_.host_resolver->LoadIntoCache(
HostPortPair("mail.example.com", 443), base::nullopt);
EXPECT_THAT(rv, IsOk());
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("https://mail.example.com/");
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
rv = trans2.Start(&request2, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
response = trans2.GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
ASSERT_THAT(ReadTransaction(&trans2, &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
}
TEST_F(HttpNetworkTransactionTest, DoNotUseSpdySessionForHttp) {
const std::string https_url = "https://www.example.org:8080/";
const std::string http_url = "http://www.example.org:8080/";
// SPDY GET for HTTPS URL
spdy::SpdySerializedFrame req1(
spdy_util_.ConstructSpdyGet(https_url.c_str(), 1, LOWEST));
MockWrite writes1[] = {
CreateMockWrite(req1, 0),
};
spdy::SpdySerializedFrame resp1(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame body1(spdy_util_.ConstructSpdyDataFrame(1, true));
MockRead reads1[] = {CreateMockRead(resp1, 1), CreateMockRead(body1, 2),
MockRead(SYNCHRONOUS, ERR_IO_PENDING, 3)};
SequencedSocketData data1(reads1, writes1);
MockConnect connect_data1(ASYNC, OK);
data1.set_connect_data(connect_data1);
// HTTP GET for the HTTP URL
MockWrite writes2[] = {
MockWrite(ASYNC, 0,
"GET / HTTP/1.1\r\n"
"Host: www.example.org:8080\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead reads2[] = {
MockRead(ASYNC, 1, "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
MockRead(ASYNC, 2, "hello"),
MockRead(ASYNC, OK, 3),
};
SequencedSocketData data2(reads2, writes2);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Start the first transaction to set up the SpdySession
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL(https_url);
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans1(LOWEST, session.get());
TestCompletionCallback callback1;
EXPECT_EQ(ERR_IO_PENDING,
trans1.Start(&request1, callback1.callback(), NetLogWithSource()));
base::RunLoop().RunUntilIdle();
EXPECT_THAT(callback1.WaitForResult(), IsOk());
EXPECT_TRUE(trans1.GetResponseInfo()->was_fetched_via_spdy);
// Now, start the HTTP request
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL(http_url);
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans2(MEDIUM, session.get());
TestCompletionCallback callback2;
EXPECT_EQ(ERR_IO_PENDING,
trans2.Start(&request2, callback2.callback(), NetLogWithSource()));
base::RunLoop().RunUntilIdle();
EXPECT_THAT(callback2.WaitForResult(), IsOk());
EXPECT_FALSE(trans2.GetResponseInfo()->was_fetched_via_spdy);
}
// Alternative service requires HTTP/2 (or SPDY), but HTTP/1.1 is negotiated
// with the alternative server. That connection should not be used.
TEST_F(HttpNetworkTransactionTest, AlternativeServiceNotOnHttp11) {
url::SchemeHostPort server("https", "www.example.org", 443);
HostPortPair alternative("www.example.org", 444);
// Negotiate HTTP/1.1 with alternative.
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP11;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
// No data should be read from the alternative, because HTTP/1.1 is
// negotiated.
StaticSocketDataProvider data;
session_deps_.socket_factory->AddSocketDataProvider(&data);
// This test documents that an alternate Job should not be used if HTTP/1.1 is
// negotiated. In order to test this, a failed connection to the server is
// mocked. This way the request relies on the alternate Job.
StaticSocketDataProvider data_refused;
data_refused.set_connect_data(MockConnect(ASYNC, ERR_CONNECTION_REFUSED));
session_deps_.socket_factory->AddSocketDataProvider(&data_refused);
// Set up alternative service for server.
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
AlternativeService alternative_service(kProtoHTTP2, alternative);
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
http_server_properties->SetHttp2AlternativeService(
server, alternative_service, expiration);
HttpRequestInfo request;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
request.method = "GET";
request.url = GURL("https://www.example.org:443");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestCompletionCallback callback;
// HTTP/2 (or SPDY) is required for alternative service, if HTTP/1.1 is
// negotiated, the alternate Job should fail with ERR_ALPN_NEGOTIATION_FAILED.
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsError(ERR_ALPN_NEGOTIATION_FAILED));
}
// A request to a server with an alternative service fires two Jobs: one to the
// server, and an alternate one to the alternative server. If the former
// succeeds, the request should succeed, even if the latter fails because
// HTTP/1.1 is negotiated which is insufficient for alternative service.
TEST_F(HttpNetworkTransactionTest, FailedAlternativeServiceIsNotUserVisible) {
url::SchemeHostPort server("https", "www.example.org", 443);
HostPortPair alternative("www.example.org", 444);
// Negotiate HTTP/1.1 with alternative.
SSLSocketDataProvider alternative_ssl(ASYNC, OK);
alternative_ssl.next_proto = kProtoHTTP11;
session_deps_.socket_factory->AddSSLSocketDataProvider(&alternative_ssl);
// No data should be read from the alternative, because HTTP/1.1 is
// negotiated.
StaticSocketDataProvider data;
session_deps_.socket_factory->AddSocketDataProvider(&data);
// Negotiate HTTP/1.1 with server.
SSLSocketDataProvider origin_ssl(ASYNC, OK);
origin_ssl.next_proto = kProtoHTTP11;
session_deps_.socket_factory->AddSSLSocketDataProvider(&origin_ssl);
MockWrite http_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
MockWrite("GET /second HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead http_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html\r\n"),
MockRead("Content-Length: 6\r\n\r\n"),
MockRead("foobar"),
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html\r\n"),
MockRead("Content-Length: 7\r\n\r\n"),
MockRead("another"),
};
StaticSocketDataProvider http_data(http_reads, http_writes);
session_deps_.socket_factory->AddSocketDataProvider(&http_data);
// Set up alternative service for server.
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
AlternativeService alternative_service(kProtoHTTP2, alternative);
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
http_server_properties->SetHttp2AlternativeService(
server, alternative_service, expiration);
HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("https://www.example.org:443");
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestCompletionCallback callback1;
int rv = trans1.Start(&request1, callback1.callback(), NetLogWithSource());
rv = callback1.GetResult(rv);
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response1 = trans1.GetResponseInfo();
ASSERT_TRUE(response1);
ASSERT_TRUE(response1->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response1->headers->GetStatusLine());
std::string response_data1;
ASSERT_THAT(ReadTransaction(&trans1, &response_data1), IsOk());
EXPECT_EQ("foobar", response_data1);
// Alternative should be marked as broken, because HTTP/1.1 is not sufficient
// for alternative service.
EXPECT_TRUE(
http_server_properties->IsAlternativeServiceBroken(alternative_service));
// Since |alternative_service| is broken, a second transaction to server
// should not start an alternate Job. It should pool to existing connection
// to server.
HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("https://www.example.org:443/second");
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestCompletionCallback callback2;
rv = trans2.Start(&request2, callback2.callback(), NetLogWithSource());
rv = callback2.GetResult(rv);
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response2 = trans2.GetResponseInfo();
ASSERT_TRUE(response2);
ASSERT_TRUE(response2->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response2->headers->GetStatusLine());
std::string response_data2;
ASSERT_THAT(ReadTransaction(&trans2, &response_data2), IsOk());
EXPECT_EQ("another", response_data2);
}
// Alternative service requires HTTP/2 (or SPDY), but there is already a
// HTTP/1.1 socket open to the alternative server. That socket should not be
// used.
TEST_F(HttpNetworkTransactionTest, AlternativeServiceShouldNotPoolToHttp11) {
url::SchemeHostPort server("https", "origin.example.org", 443);
HostPortPair alternative("alternative.example.org", 443);
std::string origin_url = "https://origin.example.org:443";
std::string alternative_url = "https://alternative.example.org:443";
// Negotiate HTTP/1.1 with alternative.example.org.
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.next_proto = kProtoHTTP11;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
// HTTP/1.1 data for |request1| and |request2|.
MockWrite http_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: alternative.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: alternative.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead http_reads[] = {
MockRead(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=iso-8859-1\r\n"
"Content-Length: 40\r\n\r\n"
"first HTTP/1.1 response from alternative"),
MockRead(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=iso-8859-1\r\n"
"Content-Length: 41\r\n\r\n"
"second HTTP/1.1 response from alternative"),
};
StaticSocketDataProvider http_data(http_reads, http_writes);
session_deps_.socket_factory->AddSocketDataProvider(&http_data);
// This test documents that an alternate Job should not pool to an already
// existing HTTP/1.1 connection. In order to test this, a failed connection
// to the server is mocked. This way |request2| relies on the alternate Job.
StaticSocketDataProvider data_refused;
data_refused.set_connect_data(MockConnect(ASYNC, ERR_CONNECTION_REFUSED));
session_deps_.socket_factory->AddSocketDataProvider(&data_refused);
// Set up alternative service for server.
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpServerProperties* http_server_properties =
session->http_server_properties();
AlternativeService alternative_service(kProtoHTTP2, alternative);
base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1);
http_server_properties->SetHttp2AlternativeService(
server, alternative_service, expiration);
// First transaction to alternative to open an HTTP/1.1 socket.
HttpRequestInfo request1;
HttpNetworkTransaction trans1(DEFAULT_PRIORITY, session.get());
request1.method = "GET";
request1.url = GURL(alternative_url);
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestCompletionCallback callback1;
int rv = trans1.Start(&request1, callback1.callback(), NetLogWithSource());
EXPECT_THAT(callback1.GetResult(rv), IsOk());
const HttpResponseInfo* response1 = trans1.GetResponseInfo();
ASSERT_TRUE(response1);
ASSERT_TRUE(response1->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response1->headers->GetStatusLine());
EXPECT_TRUE(response1->was_alpn_negotiated);
EXPECT_FALSE(response1->was_fetched_via_spdy);
std::string response_data1;
ASSERT_THAT(ReadTransaction(&trans1, &response_data1), IsOk());
EXPECT_EQ("first HTTP/1.1 response from alternative", response_data1);
// Request for origin.example.org, which has an alternative service. This
// will start two Jobs: the alternative looks for connections to pool to,
// finds one which is HTTP/1.1, and should ignore it, and should not try to
// open other connections to alternative server. The Job to server fails, so
// this request fails.
HttpRequestInfo request2;
HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
request2.method = "GET";
request2.url = GURL(origin_url);
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestCompletionCallback callback2;
rv = trans2.Start(&request2, callback2.callback(), NetLogWithSource());
EXPECT_THAT(callback2.GetResult(rv), IsError(ERR_CONNECTION_REFUSED));
// Another transaction to alternative. This is to test that the HTTP/1.1
// socket is still open and in the pool.
HttpRequestInfo request3;
HttpNetworkTransaction trans3(DEFAULT_PRIORITY, session.get());
request3.method = "GET";
request3.url = GURL(alternative_url);
request3.load_flags = 0;
request3.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestCompletionCallback callback3;
rv = trans3.Start(&request3, callback3.callback(), NetLogWithSource());
EXPECT_THAT(callback3.GetResult(rv), IsOk());
const HttpResponseInfo* response3 = trans3.GetResponseInfo();
ASSERT_TRUE(response3);
ASSERT_TRUE(response3->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response3->headers->GetStatusLine());
EXPECT_TRUE(response3->was_alpn_negotiated);
EXPECT_FALSE(response3->was_fetched_via_spdy);
std::string response_data3;
ASSERT_THAT(ReadTransaction(&trans3, &response_data3), IsOk());
EXPECT_EQ("second HTTP/1.1 response from alternative", response_data3);
}
TEST_F(HttpNetworkTransactionTest, DoNotUseSpdySessionForHttpOverTunnel) {
const std::string https_url = "https://www.example.org:8080/";
const std::string http_url = "http://www.example.org:8080/";
// Separate SPDY util instance for naked and wrapped requests.
SpdyTestUtil spdy_util_wrapped;
// SPDY GET for HTTPS URL (through CONNECT tunnel)
const HostPortPair host_port_pair("www.example.org", 8080);
spdy::SpdySerializedFrame connect(spdy_util_.ConstructSpdyConnect(
nullptr, 0, 1, HttpProxyConnectJob::kH2QuicTunnelPriority,
host_port_pair));
spdy::SpdySerializedFrame req1(
spdy_util_wrapped.ConstructSpdyGet(https_url.c_str(), 1, LOWEST));
spdy::SpdySerializedFrame wrapped_req1(
spdy_util_.ConstructWrappedSpdyFrame(req1, 1));
// SPDY GET for HTTP URL (through the proxy, but not the tunnel).
spdy::SpdyHeaderBlock req2_block;
req2_block[spdy::kHttp2MethodHeader] = "GET";
req2_block[spdy::kHttp2AuthorityHeader] = "www.example.org:8080";
req2_block[spdy::kHttp2SchemeHeader] = "http";
req2_block[spdy::kHttp2PathHeader] = "/";
spdy::SpdySerializedFrame req2(
spdy_util_.ConstructSpdyHeaders(3, std::move(req2_block), MEDIUM, true));
MockWrite writes1[] = {
CreateMockWrite(connect, 0), CreateMockWrite(wrapped_req1, 2),
CreateMockWrite(req2, 6),
};
spdy::SpdySerializedFrame conn_resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame resp1(
spdy_util_wrapped.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame body1(
spdy_util_wrapped.ConstructSpdyDataFrame(1, true));
spdy::SpdySerializedFrame wrapped_resp1(
spdy_util_wrapped.ConstructWrappedSpdyFrame(resp1, 1));
spdy::SpdySerializedFrame wrapped_body1(
spdy_util_wrapped.ConstructWrappedSpdyFrame(body1, 1));
spdy::SpdySerializedFrame resp2(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 3));
spdy::SpdySerializedFrame body2(spdy_util_.ConstructSpdyDataFrame(3, true));
MockRead reads1[] = {
CreateMockRead(conn_resp, 1),
MockRead(ASYNC, ERR_IO_PENDING, 3),
CreateMockRead(wrapped_resp1, 4),
CreateMockRead(wrapped_body1, 5),
MockRead(ASYNC, ERR_IO_PENDING, 7),
CreateMockRead(resp2, 8),
CreateMockRead(body2, 9),
MockRead(SYNCHRONOUS, ERR_IO_PENDING, 10),
};
SequencedSocketData data1(reads1, writes1);
MockConnect connect_data1(ASYNC, OK);
data1.set_connect_data(connect_data1);
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"HTTPS proxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
TestNetLog log;
session_deps_.net_log = &log;
SSLSocketDataProvider ssl1(ASYNC, OK); // to the proxy
ssl1.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
SSLSocketDataProvider ssl2(ASYNC, OK); // to the server
ssl2.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
std::unique_ptr<HttpNetworkSession> session = CreateSession(&session_deps_);
// Start the first transaction to set up the SpdySession
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL(https_url);
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans1(LOWEST, session.get());
TestCompletionCallback callback1;
int rv = trans1.Start(&request1, callback1.callback(), NetLogWithSource());
// This pause is a hack to avoid running into https://crbug.com/497228.
data1.RunUntilPaused();
base::RunLoop().RunUntilIdle();
data1.Resume();
EXPECT_THAT(callback1.GetResult(rv), IsOk());
EXPECT_TRUE(trans1.GetResponseInfo()->was_fetched_via_spdy);
LoadTimingInfo load_timing_info1;
EXPECT_TRUE(trans1.GetLoadTimingInfo(&load_timing_info1));
TestLoadTimingNotReusedWithPac(load_timing_info1,
CONNECT_TIMING_HAS_SSL_TIMES);
// Now, start the HTTP request.
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL(http_url);
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans2(MEDIUM, session.get());
TestCompletionCallback callback2;
rv = trans2.Start(&request2, callback2.callback(), NetLogWithSource());
// This pause is a hack to avoid running into https://crbug.com/497228.
data1.RunUntilPaused();
base::RunLoop().RunUntilIdle();
data1.Resume();
EXPECT_THAT(callback2.GetResult(rv), IsOk());
EXPECT_TRUE(trans2.GetResponseInfo()->was_fetched_via_spdy);
LoadTimingInfo load_timing_info2;
EXPECT_TRUE(trans2.GetLoadTimingInfo(&load_timing_info2));
// The established SPDY sessions is considered reused by the HTTP request.
TestLoadTimingReusedWithPac(load_timing_info2);
// HTTP requests over a SPDY session should have a different connection
// socket_log_id than requests over a tunnel.
EXPECT_NE(load_timing_info1.socket_log_id, load_timing_info2.socket_log_id);
}
// Test that in the case where we have a SPDY session to a SPDY proxy
// that we do not pool other origins that resolve to the same IP when
// the certificate does not match the new origin.
// http://crbug.com/134690
TEST_F(HttpNetworkTransactionTest, DoNotUseSpdySessionIfCertDoesNotMatch) {
const std::string url1 = "http://www.example.org/";
const std::string url2 = "https://news.example.org/";
const std::string ip_addr = "1.2.3.4";
// Second SpdyTestUtil instance for the second socket.
SpdyTestUtil spdy_util_secure;
// SPDY GET for HTTP URL (through SPDY proxy)
spdy::SpdyHeaderBlock headers(
spdy_util_.ConstructGetHeaderBlockForProxy("http://www.example.org/"));
spdy::SpdySerializedFrame req1(
spdy_util_.ConstructSpdyHeaders(1, std::move(headers), LOWEST, true));
MockWrite writes1[] = {
CreateMockWrite(req1, 0),
};
spdy::SpdySerializedFrame resp1(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame body1(spdy_util_.ConstructSpdyDataFrame(1, true));
MockRead reads1[] = {
MockRead(ASYNC, ERR_IO_PENDING, 1), CreateMockRead(resp1, 2),
CreateMockRead(body1, 3), MockRead(ASYNC, OK, 4), // EOF
};
SequencedSocketData data1(reads1, writes1);
IPAddress ip;
ASSERT_TRUE(ip.AssignFromIPLiteral(ip_addr));
IPEndPoint peer_addr = IPEndPoint(ip, 443);
MockConnect connect_data1(ASYNC, OK, peer_addr);
data1.set_connect_data(connect_data1);
// SPDY GET for HTTPS URL (direct)
spdy::SpdySerializedFrame req2(
spdy_util_secure.ConstructSpdyGet(url2.c_str(), 1, MEDIUM));
MockWrite writes2[] = {
CreateMockWrite(req2, 0),
};
spdy::SpdySerializedFrame resp2(
spdy_util_secure.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame body2(
spdy_util_secure.ConstructSpdyDataFrame(1, true));
MockRead reads2[] = {CreateMockRead(resp2, 1), CreateMockRead(body2, 2),
MockRead(ASYNC, OK, 3)};
SequencedSocketData data2(reads2, writes2);
MockConnect connect_data2(ASYNC, OK);
data2.set_connect_data(connect_data2);
// Set up a proxy config that sends HTTP requests to a proxy, and
// all others direct.
ProxyConfig proxy_config;
proxy_config.proxy_rules().ParseFromString("http=https://proxy:443");
session_deps_.proxy_resolution_service =
std::make_unique<ProxyResolutionService>(
std::make_unique<ProxyConfigServiceFixed>(ProxyConfigWithAnnotation(
proxy_config, TRAFFIC_ANNOTATION_FOR_TESTS)),
nullptr, nullptr);
SSLSocketDataProvider ssl1(ASYNC, OK); // to the proxy
ssl1.next_proto = kProtoHTTP2;
// Load a valid cert. Note, that this does not need to
// be valid for proxy because the MockSSLClientSocket does
// not actually verify it. But SpdySession will use this
// to see if it is valid for the new origin
ssl1.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
ASSERT_TRUE(ssl1.ssl_info.cert);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
SSLSocketDataProvider ssl2(ASYNC, OK); // to the server
ssl2.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
session_deps_.host_resolver = std::make_unique<MockCachingHostResolver>();
session_deps_.host_resolver->rules()->AddRule("news.example.org", ip_addr);
session_deps_.host_resolver->rules()->AddRule("proxy", ip_addr);
std::unique_ptr<HttpNetworkSession> session = CreateSession(&session_deps_);
// Start the first transaction to set up the SpdySession
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL(url1);
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans1(LOWEST, session.get());
TestCompletionCallback callback1;
ASSERT_EQ(ERR_IO_PENDING,
trans1.Start(&request1, callback1.callback(), NetLogWithSource()));
// This pause is a hack to avoid running into https://crbug.com/497228.
data1.RunUntilPaused();
base::RunLoop().RunUntilIdle();
data1.Resume();
EXPECT_THAT(callback1.WaitForResult(), IsOk());
EXPECT_TRUE(trans1.GetResponseInfo()->was_fetched_via_spdy);
// Now, start the HTTP request
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL(url2);
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans2(MEDIUM, session.get());
TestCompletionCallback callback2;
EXPECT_EQ(ERR_IO_PENDING,
trans2.Start(&request2, callback2.callback(), NetLogWithSource()));
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(callback2.have_result());
EXPECT_THAT(callback2.WaitForResult(), IsOk());
EXPECT_TRUE(trans2.GetResponseInfo()->was_fetched_via_spdy);
}
// Test to verify that a failed socket read (due to an ERR_CONNECTION_CLOSED
// error) in SPDY session, removes the socket from pool and closes the SPDY
// session. Verify that new url's from the same HttpNetworkSession (and a new
// SpdySession) do work. http://crbug.com/224701
TEST_F(HttpNetworkTransactionTest, ErrorSocketNotConnected) {
const std::string https_url = "https://www.example.org/";
MockRead reads1[] = {
MockRead(SYNCHRONOUS, ERR_CONNECTION_CLOSED, 0)
};
SequencedSocketData data1(reads1, base::span<MockWrite>());
spdy::SpdySerializedFrame req2(
spdy_util_.ConstructSpdyGet(https_url.c_str(), 1, MEDIUM));
MockWrite writes2[] = {
CreateMockWrite(req2, 0),
};
spdy::SpdySerializedFrame resp2(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame body2(spdy_util_.ConstructSpdyDataFrame(1, true));
MockRead reads2[] = {
CreateMockRead(resp2, 1), CreateMockRead(body2, 2),
MockRead(ASYNC, OK, 3) // EOF
};
SequencedSocketData data2(reads2, writes2);
SSLSocketDataProvider ssl1(ASYNC, OK);
ssl1.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
SSLSocketDataProvider ssl2(ASYNC, OK);
ssl2.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
std::unique_ptr<HttpNetworkSession> session(
SpdySessionDependencies::SpdyCreateSession(&session_deps_));
// Start the first transaction to set up the SpdySession and verify that
// connection was closed.
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL(https_url);
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans1(MEDIUM, session.get());
TestCompletionCallback callback1;
EXPECT_EQ(ERR_IO_PENDING,
trans1.Start(&request1, callback1.callback(), NetLogWithSource()));
EXPECT_THAT(callback1.WaitForResult(), IsError(ERR_CONNECTION_CLOSED));
// Now, start the second request and make sure it succeeds.
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL(https_url);
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans2(MEDIUM, session.get());
TestCompletionCallback callback2;
EXPECT_EQ(ERR_IO_PENDING,
trans2.Start(&request2, callback2.callback(), NetLogWithSource()));
ASSERT_THAT(callback2.WaitForResult(), IsOk());
EXPECT_TRUE(trans2.GetResponseInfo()->was_fetched_via_spdy);
}
TEST_F(HttpNetworkTransactionTest, CloseIdleSpdySessionToOpenNewOne) {
ClientSocketPoolManager::set_max_sockets_per_group(
HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
ClientSocketPoolManager::set_max_sockets_per_pool(
HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
// Use two different hosts with different IPs so they don't get pooled.
session_deps_.host_resolver->rules()->AddRule("www.a.com", "10.0.0.1");
session_deps_.host_resolver->rules()->AddRule("www.b.com", "10.0.0.2");
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
SSLSocketDataProvider ssl1(ASYNC, OK);
ssl1.next_proto = kProtoHTTP2;
SSLSocketDataProvider ssl2(ASYNC, OK);
ssl2.next_proto = kProtoHTTP2;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
spdy::SpdySerializedFrame host1_req(
spdy_util_.ConstructSpdyGet("https://www.a.com", 1, DEFAULT_PRIORITY));
MockWrite spdy1_writes[] = {
CreateMockWrite(host1_req, 0),
};
spdy::SpdySerializedFrame host1_resp(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame host1_resp_body(
spdy_util_.ConstructSpdyDataFrame(1, true));
MockRead spdy1_reads[] = {
CreateMockRead(host1_resp, 1), CreateMockRead(host1_resp_body, 2),
MockRead(SYNCHRONOUS, ERR_IO_PENDING, 3),
};
// Use a separate test instance for the separate SpdySession that will be
// created.
SpdyTestUtil spdy_util_2;
SequencedSocketData spdy1_data(spdy1_reads, spdy1_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy1_data);
spdy::SpdySerializedFrame host2_req(
spdy_util_2.ConstructSpdyGet("https://www.b.com", 1, DEFAULT_PRIORITY));
MockWrite spdy2_writes[] = {
CreateMockWrite(host2_req, 0),
};
spdy::SpdySerializedFrame host2_resp(
spdy_util_2.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame host2_resp_body(
spdy_util_2.ConstructSpdyDataFrame(1, true));
MockRead spdy2_reads[] = {
CreateMockRead(host2_resp, 1), CreateMockRead(host2_resp_body, 2),
MockRead(SYNCHRONOUS, ERR_IO_PENDING, 3),
};
SequencedSocketData spdy2_data(spdy2_reads, spdy2_writes);
session_deps_.socket_factory->AddSocketDataProvider(&spdy2_data);
MockWrite http_write[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.a.com\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead http_read[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 6\r\n\r\n"),
MockRead("hello!"),
};
StaticSocketDataProvider http_data(http_read, http_write);
session_deps_.socket_factory->AddSocketDataProvider(&http_data);
HostPortPair host_port_pair_a("www.a.com", 443);
SpdySessionKey spdy_session_key_a(
host_port_pair_a, ProxyServer::Direct(), PRIVACY_MODE_DISABLED,
SpdySessionKey::IsProxySession::kFalse, SocketTag());
EXPECT_FALSE(
HasSpdySession(session->spdy_session_pool(), spdy_session_key_a));
TestCompletionCallback callback;
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("https://www.a.com/");
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
std::string response_data;
ASSERT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
trans.reset();
EXPECT_TRUE(
HasSpdySession(session->spdy_session_pool(), spdy_session_key_a));
HostPortPair host_port_pair_b("www.b.com", 443);
SpdySessionKey spdy_session_key_b(
host_port_pair_b, ProxyServer::Direct(), PRIVACY_MODE_DISABLED,
SpdySessionKey::IsProxySession::kFalse, SocketTag());
EXPECT_FALSE(
HasSpdySession(session->spdy_session_pool(), spdy_session_key_b));
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("https://www.b.com/");
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
rv = trans->Start(&request2, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
ASSERT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
EXPECT_FALSE(
HasSpdySession(session->spdy_session_pool(), spdy_session_key_a));
EXPECT_TRUE(
HasSpdySession(session->spdy_session_pool(), spdy_session_key_b));
HostPortPair host_port_pair_a1("www.a.com", 80);
SpdySessionKey spdy_session_key_a1(
host_port_pair_a1, ProxyServer::Direct(), PRIVACY_MODE_DISABLED,
SpdySessionKey::IsProxySession::kFalse, SocketTag());
EXPECT_FALSE(
HasSpdySession(session->spdy_session_pool(), spdy_session_key_a1));
HttpRequestInfo request3;
request3.method = "GET";
request3.url = GURL("http://www.a.com/");
request3.load_flags = 0;
request3.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
rv = trans->Start(&request3, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200 OK", response->headers->GetStatusLine());
EXPECT_FALSE(response->was_fetched_via_spdy);
EXPECT_FALSE(response->was_alpn_negotiated);
ASSERT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
EXPECT_FALSE(
HasSpdySession(session->spdy_session_pool(), spdy_session_key_a));
EXPECT_FALSE(
HasSpdySession(session->spdy_session_pool(), spdy_session_key_b));
}
TEST_F(HttpNetworkTransactionTest, HttpSyncConnectError) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockConnect mock_connect(SYNCHRONOUS, ERR_NAME_NOT_RESOLVED);
StaticSocketDataProvider data;
data.set_connect_data(mock_connect);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_NAME_NOT_RESOLVED));
// We don't care whether this succeeds or fails, but it shouldn't crash.
HttpRequestHeaders request_headers;
trans.GetFullRequestHeaders(&request_headers);
ConnectionAttempts attempts;
trans.GetConnectionAttempts(&attempts);
ASSERT_EQ(1u, attempts.size());
EXPECT_THAT(attempts[0].result, IsError(ERR_NAME_NOT_RESOLVED));
IPEndPoint endpoint;
EXPECT_FALSE(trans.GetRemoteEndpoint(&endpoint));
EXPECT_TRUE(endpoint.address().empty());
}
TEST_F(HttpNetworkTransactionTest, HttpAsyncConnectError) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockConnect mock_connect(ASYNC, ERR_NAME_NOT_RESOLVED);
StaticSocketDataProvider data;
data.set_connect_data(mock_connect);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_NAME_NOT_RESOLVED));
// We don't care whether this succeeds or fails, but it shouldn't crash.
HttpRequestHeaders request_headers;
trans.GetFullRequestHeaders(&request_headers);
ConnectionAttempts attempts;
trans.GetConnectionAttempts(&attempts);
ASSERT_EQ(1u, attempts.size());
EXPECT_THAT(attempts[0].result, IsError(ERR_NAME_NOT_RESOLVED));
IPEndPoint endpoint;
EXPECT_FALSE(trans.GetRemoteEndpoint(&endpoint));
EXPECT_TRUE(endpoint.address().empty());
}
TEST_F(HttpNetworkTransactionTest, HttpSyncWriteError) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
};
MockRead data_reads[] = {
MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
HttpRequestHeaders request_headers;
EXPECT_TRUE(trans.GetFullRequestHeaders(&request_headers));
EXPECT_TRUE(request_headers.HasHeader("Host"));
}
TEST_F(HttpNetworkTransactionTest, HttpAsyncWriteError) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite(ASYNC, ERR_CONNECTION_RESET),
};
MockRead data_reads[] = {
MockRead(SYNCHRONOUS, ERR_UNEXPECTED), // Should not be reached.
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
HttpRequestHeaders request_headers;
EXPECT_TRUE(trans.GetFullRequestHeaders(&request_headers));
EXPECT_TRUE(request_headers.HasHeader("Host"));
}
TEST_F(HttpNetworkTransactionTest, HttpSyncReadError) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead(SYNCHRONOUS, ERR_CONNECTION_RESET),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
HttpRequestHeaders request_headers;
EXPECT_TRUE(trans.GetFullRequestHeaders(&request_headers));
EXPECT_TRUE(request_headers.HasHeader("Host"));
}
TEST_F(HttpNetworkTransactionTest, HttpAsyncReadError) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead(ASYNC, ERR_CONNECTION_RESET),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
HttpRequestHeaders request_headers;
EXPECT_TRUE(trans.GetFullRequestHeaders(&request_headers));
EXPECT_TRUE(request_headers.HasHeader("Host"));
}
TEST_F(HttpNetworkTransactionTest, GetFullRequestHeadersIncludesExtraHeader) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.extra_headers.SetHeader("X-Foo", "bar");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"X-Foo: bar\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"
"Content-Length: 5\r\n\r\n"
"hello"),
MockRead(ASYNC, ERR_UNEXPECTED),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
HttpRequestHeaders request_headers;
EXPECT_TRUE(trans.GetFullRequestHeaders(&request_headers));
std::string foo;
EXPECT_TRUE(request_headers.GetHeader("X-Foo", &foo));
EXPECT_EQ("bar", foo);
}
// Tests that when a used socket is returned to the SSL socket pool, it's closed
// if the transport socket pool is stalled on the global socket limit.
TEST_F(HttpNetworkTransactionTest, CloseSSLSocketOnIdleForHttpRequest) {
ClientSocketPoolManager::set_max_sockets_per_group(
HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
ClientSocketPoolManager::set_max_sockets_per_pool(
HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
// Set up SSL request.
HttpRequestInfo ssl_request;
ssl_request.method = "GET";
ssl_request.url = GURL("https://www.example.org/");
ssl_request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite ssl_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead ssl_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 11\r\n\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider ssl_data(ssl_reads, ssl_writes);
session_deps_.socket_factory->AddSocketDataProvider(&ssl_data);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
// Set up HTTP request.
HttpRequestInfo http_request;
http_request.method = "GET";
http_request.url = GURL("http://www.example.org/");
http_request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite http_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead http_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 7\r\n\r\n"),
MockRead("falafel"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider http_data(http_reads, http_writes);
session_deps_.socket_factory->AddSocketDataProvider(&http_data);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Start the SSL request.
TestCompletionCallback ssl_callback;
HttpNetworkTransaction ssl_trans(DEFAULT_PRIORITY, session.get());
ASSERT_EQ(ERR_IO_PENDING,
ssl_trans.Start(&ssl_request, ssl_callback.callback(),
NetLogWithSource()));
// Start the HTTP request. Pool should stall.
TestCompletionCallback http_callback;
HttpNetworkTransaction http_trans(DEFAULT_PRIORITY, session.get());
ASSERT_EQ(ERR_IO_PENDING,
http_trans.Start(&http_request, http_callback.callback(),
NetLogWithSource()));
EXPECT_TRUE(IsTransportSocketPoolStalled(session.get()));
// Wait for response from SSL request.
ASSERT_THAT(ssl_callback.WaitForResult(), IsOk());
std::string response_data;
ASSERT_THAT(ReadTransaction(&ssl_trans, &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
// The SSL socket should automatically be closed, so the HTTP request can
// start.
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
ASSERT_FALSE(IsTransportSocketPoolStalled(session.get()));
// The HTTP request can now complete.
ASSERT_THAT(http_callback.WaitForResult(), IsOk());
ASSERT_THAT(ReadTransaction(&http_trans, &response_data), IsOk());
EXPECT_EQ("falafel", response_data);
EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
}
// Tests that when a SSL connection is established but there's no corresponding
// request that needs it, the new socket is closed if the transport socket pool
// is stalled on the global socket limit.
TEST_F(HttpNetworkTransactionTest, CloseSSLSocketOnIdleForHttpRequest2) {
ClientSocketPoolManager::set_max_sockets_per_group(
HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
ClientSocketPoolManager::set_max_sockets_per_pool(
HttpNetworkSession::NORMAL_SOCKET_POOL, 1);
// Set up an ssl request.
HttpRequestInfo ssl_request;
ssl_request.method = "GET";
ssl_request.url = GURL("https://www.foopy.com/");
ssl_request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// No data will be sent on the SSL socket.
StaticSocketDataProvider ssl_data;
session_deps_.socket_factory->AddSocketDataProvider(&ssl_data);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
// Set up HTTP request.
HttpRequestInfo http_request;
http_request.method = "GET";
http_request.url = GURL("http://www.example.org/");
http_request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite http_writes[] = {
MockWrite(
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead http_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 7\r\n\r\n"),
MockRead("falafel"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider http_data(http_reads, http_writes);
session_deps_.socket_factory->AddSocketDataProvider(&http_data);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Preconnect an SSL socket. A preconnect is needed because connect jobs are
// cancelled when a normal transaction is cancelled.
HttpStreamFactory* http_stream_factory = session->http_stream_factory();
http_stream_factory->PreconnectStreams(1, ssl_request);
EXPECT_EQ(0, GetIdleSocketCountInTransportSocketPool(session.get()));
// Start the HTTP request. Pool should stall.
TestCompletionCallback http_callback;
HttpNetworkTransaction http_trans(DEFAULT_PRIORITY, session.get());
ASSERT_EQ(ERR_IO_PENDING,
http_trans.Start(&http_request, http_callback.callback(),
NetLogWithSource()));
EXPECT_TRUE(IsTransportSocketPoolStalled(session.get()));
// The SSL connection will automatically be closed once the connection is
// established, to let the HTTP request start.
ASSERT_THAT(http_callback.WaitForResult(), IsOk());
std::string response_data;
ASSERT_THAT(ReadTransaction(&http_trans, &response_data), IsOk());
EXPECT_EQ("falafel", response_data);
EXPECT_EQ(1, GetIdleSocketCountInTransportSocketPool(session.get()));
}
TEST_F(HttpNetworkTransactionTest, PostReadsErrorResponseAfterReset) {
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(
std::make_unique<UploadBytesElementReader>("foo", 3));
ElementsUploadDataStream upload_data_stream(std::move(element_readers), 0);
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.foo.com/");
request.upload_data_stream = &upload_data_stream;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Send headers successfully, but get an error while sending the body.
MockWrite data_writes[] = {
MockWrite("POST / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 3\r\n\r\n"),
MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 400 Not OK\r\n\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.0 400 Not OK", response->headers->GetStatusLine());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello world", response_data);
}
// This test makes sure the retry logic doesn't trigger when reading an error
// response from a server that rejected a POST with a CONNECTION_RESET.
TEST_F(HttpNetworkTransactionTest,
PostReadsErrorResponseAfterResetOnReusedSocket) {
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
MockWrite data_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n\r\n"),
MockWrite("POST / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 3\r\n\r\n"),
MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
};
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 Peachy\r\n"
"Content-Length: 14\r\n\r\n"),
MockRead("first response"),
MockRead("HTTP/1.1 400 Not OK\r\n"
"Content-Length: 15\r\n\r\n"),
MockRead("second response"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("http://www.foo.com/");
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
auto trans1 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans1->Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response1 = trans1->GetResponseInfo();
ASSERT_TRUE(response1);
EXPECT_TRUE(response1->headers);
EXPECT_EQ("HTTP/1.1 200 Peachy", response1->headers->GetStatusLine());
std::string response_data1;
rv = ReadTransaction(trans1.get(), &response_data1);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("first response", response_data1);
// Delete the transaction to release the socket back into the socket pool.
trans1.reset();
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(
std::make_unique<UploadBytesElementReader>("foo", 3));
ElementsUploadDataStream upload_data_stream(std::move(element_readers), 0);
HttpRequestInfo request2;
request2.method = "POST";
request2.url = GURL("http://www.foo.com/");
request2.upload_data_stream = &upload_data_stream;
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
HttpNetworkTransaction trans2(DEFAULT_PRIORITY, session.get());
rv = trans2.Start(&request2, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response2 = trans2.GetResponseInfo();
ASSERT_TRUE(response2);
EXPECT_TRUE(response2->headers);
EXPECT_EQ("HTTP/1.1 400 Not OK", response2->headers->GetStatusLine());
std::string response_data2;
rv = ReadTransaction(&trans2, &response_data2);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("second response", response_data2);
}
TEST_F(HttpNetworkTransactionTest,
PostReadsErrorResponseAfterResetPartialBodySent) {
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(
std::make_unique<UploadBytesElementReader>("foo", 3));
ElementsUploadDataStream upload_data_stream(std::move(element_readers), 0);
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.foo.com/");
request.upload_data_stream = &upload_data_stream;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Send headers successfully, but get an error while sending the body.
MockWrite data_writes[] = {
MockWrite("POST / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 3\r\n\r\n"
"fo"),
MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 400 Not OK\r\n\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.0 400 Not OK", response->headers->GetStatusLine());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello world", response_data);
}
// This tests the more common case than the previous test, where headers and
// body are not merged into a single request.
TEST_F(HttpNetworkTransactionTest, ChunkedPostReadsErrorResponseAfterReset) {
ChunkedUploadDataStream upload_data_stream(0);
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.foo.com/");
request.upload_data_stream = &upload_data_stream;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Send headers successfully, but get an error while sending the body.
MockWrite data_writes[] = {
MockWrite("POST / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n"
"Transfer-Encoding: chunked\r\n\r\n"),
MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 400 Not OK\r\n\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
// Make sure the headers are sent before adding a chunk. This ensures that
// they can't be merged with the body in a single send. Not currently
// necessary since a chunked body is never merged with headers, but this makes
// the test more future proof.
base::RunLoop().RunUntilIdle();
upload_data_stream.AppendData("last chunk", 10, true);
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.0 400 Not OK", response->headers->GetStatusLine());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello world", response_data);
}
TEST_F(HttpNetworkTransactionTest, PostReadsErrorResponseAfterResetAnd100) {
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(
std::make_unique<UploadBytesElementReader>("foo", 3));
ElementsUploadDataStream upload_data_stream(std::move(element_readers), 0);
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.foo.com/");
request.upload_data_stream = &upload_data_stream;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite("POST / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 3\r\n\r\n"),
MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 100 Continue\r\n\r\n"),
MockRead("HTTP/1.0 400 Not OK\r\n\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.0 400 Not OK", response->headers->GetStatusLine());
std::string response_data;
rv = ReadTransaction(&trans, &response_data);
EXPECT_THAT(rv, IsOk());
EXPECT_EQ("hello world", response_data);
}
TEST_F(HttpNetworkTransactionTest, PostIgnoresNonErrorResponseAfterReset) {
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(
std::make_unique<UploadBytesElementReader>("foo", 3));
ElementsUploadDataStream upload_data_stream(std::move(element_readers), 0);
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.foo.com/");
request.upload_data_stream = &upload_data_stream;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Send headers successfully, but get an error while sending the body.
MockWrite data_writes[] = {
MockWrite("POST / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 3\r\n\r\n"),
MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 Just Dandy\r\n\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
}
TEST_F(HttpNetworkTransactionTest,
PostIgnoresNonErrorResponseAfterResetAnd100) {
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(
std::make_unique<UploadBytesElementReader>("foo", 3));
ElementsUploadDataStream upload_data_stream(std::move(element_readers), 0);
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.foo.com/");
request.upload_data_stream = &upload_data_stream;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Send headers successfully, but get an error while sending the body.
MockWrite data_writes[] = {
MockWrite("POST / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 3\r\n\r\n"),
MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 100 Continue\r\n\r\n"),
MockRead("HTTP/1.0 302 Redirect\r\n"),
MockRead("Location: http://somewhere-else.com/\r\n"),
MockRead("Content-Length: 0\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
}
TEST_F(HttpNetworkTransactionTest, PostIgnoresHttp09ResponseAfterReset) {
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(
std::make_unique<UploadBytesElementReader>("foo", 3));
ElementsUploadDataStream upload_data_stream(std::move(element_readers), 0);
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.foo.com/");
request.upload_data_stream = &upload_data_stream;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Send headers successfully, but get an error while sending the body.
MockWrite data_writes[] = {
MockWrite("POST / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 3\r\n\r\n"),
MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
};
MockRead data_reads[] = {
MockRead("HTTP 0.9 rocks!"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
}
TEST_F(HttpNetworkTransactionTest, PostIgnoresPartial400HeadersAfterReset) {
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(
std::make_unique<UploadBytesElementReader>("foo", 3));
ElementsUploadDataStream upload_data_stream(std::move(element_readers), 0);
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.foo.com/");
request.upload_data_stream = &upload_data_stream;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Send headers successfully, but get an error while sending the body.
MockWrite data_writes[] = {
MockWrite("POST / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 3\r\n\r\n"),
MockWrite(SYNCHRONOUS, ERR_CONNECTION_RESET),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 400 Not a Full Response\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_CONNECTION_RESET));
}
#if BUILDFLAG(ENABLE_WEBSOCKETS)
namespace {
void AddWebSocketHeaders(HttpRequestHeaders* headers) {
headers->SetHeader("Connection", "Upgrade");
headers->SetHeader("Upgrade", "websocket");
headers->SetHeader("Origin", "http://www.example.org");
headers->SetHeader("Sec-WebSocket-Version", "13");
}
} // namespace
TEST_F(HttpNetworkTransactionTest, CreateWebSocketHandshakeStream) {
for (bool secure : {true, false}) {
MockWrite data_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: Upgrade\r\n"
"Upgrade: websocket\r\n"
"Origin: http://www.example.org\r\n"
"Sec-WebSocket-Version: 13\r\n"
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
"Sec-WebSocket-Extensions: permessage-deflate; "
"client_max_window_bits\r\n\r\n")};
MockRead data_reads[] = {
MockRead("HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n")};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(ASYNC, OK);
if (secure)
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
HttpRequestInfo request;
request.method = "GET";
request.url =
GURL(secure ? "ws://www.example.org/" : "wss://www.example.org/");
AddWebSocketHeaders(&request.extra_headers);
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestWebSocketHandshakeStreamCreateHelper
websocket_handshake_stream_create_helper;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(LOW, session.get());
trans.SetWebSocketHandshakeStreamCreateHelper(
&websocket_handshake_stream_create_helper);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
const HttpStreamRequest* stream_request = trans.stream_request_.get();
ASSERT_TRUE(stream_request);
EXPECT_EQ(&websocket_handshake_stream_create_helper,
stream_request->websocket_handshake_stream_create_helper());
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
EXPECT_TRUE(data.AllReadDataConsumed());
EXPECT_TRUE(data.AllWriteDataConsumed());
}
}
// Verify that proxy headers are not sent to the destination server when
// establishing a tunnel for a secure WebSocket connection.
TEST_F(HttpNetworkTransactionTest, ProxyHeadersNotSentOverWssTunnel) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("wss://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
AddWebSocketHeaders(&request.extra_headers);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Since a proxy is configured, try to establish a tunnel.
MockWrite data_writes[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
// After calling trans->RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: Upgrade\r\n"
"Upgrade: websocket\r\n"
"Origin: http://www.example.org\r\n"
"Sec-WebSocket-Version: 13\r\n"
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
"Sec-WebSocket-Extensions: permessage-deflate; "
"client_max_window_bits\r\n\r\n")};
// The proxy responds to the connect with a 407, using a persistent
// connection.
MockRead data_reads[] = {
// No credentials.
MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"
"Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"
"Content-Length: 0\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
MockRead("HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n")};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestWebSocketHandshakeStreamCreateHelper websocket_stream_create_helper;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
trans->SetWebSocketHandshakeStreamCreateHelper(
&websocket_stream_create_helper);
{
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
}
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(407, response->headers->response_code());
{
TestCompletionCallback callback;
int rv = trans->RestartWithAuth(AuthCredentials(kFoo, kBar),
callback.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
}
response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(101, response->headers->response_code());
trans.reset();
session->CloseAllConnections();
}
// Verify that proxy headers are not sent to the destination server when
// establishing a tunnel for an insecure WebSocket connection.
// This requires the authentication info to be injected into the auth cache
// due to crbug.com/395064
// TODO(ricea): Change to use a 407 response once issue 395064 is fixed.
TEST_F(HttpNetworkTransactionTest, ProxyHeadersNotSentOverWsTunnel) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("ws://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
AddWebSocketHeaders(&request.extra_headers);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
MockWrite data_writes[] = {
// Try to establish a tunnel for the WebSocket connection, with
// credentials. Because WebSockets have a separate set of socket pools,
// they cannot and will not use the same TCP/IP connection as the
// preflight HTTP request.
MockWrite("CONNECT www.example.org:80 HTTP/1.1\r\n"
"Host: www.example.org:80\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: Upgrade\r\n"
"Upgrade: websocket\r\n"
"Origin: http://www.example.org\r\n"
"Sec-WebSocket-Version: 13\r\n"
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
"Sec-WebSocket-Extensions: permessage-deflate; "
"client_max_window_bits\r\n\r\n")};
MockRead data_reads[] = {
// HTTP CONNECT with credentials.
MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
// WebSocket connection established inside tunnel.
MockRead("HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n")};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
session->http_auth_cache()->Add(
GURL("http://myproxy:70/"), "MyRealm1", HttpAuth::AUTH_SCHEME_BASIC,
"Basic realm=MyRealm1", AuthCredentials(kFoo, kBar), "/");
TestWebSocketHandshakeStreamCreateHelper websocket_stream_create_helper;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
trans->SetWebSocketHandshakeStreamCreateHelper(
&websocket_stream_create_helper);
TestCompletionCallback callback;
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(101, response->headers->response_code());
trans.reset();
session->CloseAllConnections();
}
// WebSockets over QUIC is not supported, including over QUIC proxies.
TEST_F(HttpNetworkTransactionTest, WebSocketNotSentOverQuicProxy) {
for (bool secure : {true, false}) {
SCOPED_TRACE(secure);
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"QUIC myproxy.org:443", TRAFFIC_ANNOTATION_FOR_TESTS);
session_deps_.enable_quic = true;
HttpRequestInfo request;
request.url =
GURL(secure ? "ws://www.example.org/" : "wss://www.example.org/");
AddWebSocketHeaders(&request.extra_headers);
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestWebSocketHandshakeStreamCreateHelper
websocket_handshake_stream_create_helper;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(LOW, session.get());
trans.SetWebSocketHandshakeStreamCreateHelper(
&websocket_handshake_stream_create_helper);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_NO_SUPPORTED_PROXIES));
}
}
#endif // BUILDFLAG(ENABLE_WEBSOCKETS)
TEST_F(HttpNetworkTransactionTest, TotalNetworkBytesPost) {
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(
std::make_unique<UploadBytesElementReader>("foo", 3));
ElementsUploadDataStream upload_data_stream(std::move(element_readers), 0);
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.foo.com/");
request.upload_data_stream = &upload_data_stream;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite("POST / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 3\r\n\r\n"),
MockWrite("foo"),
};
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n\r\n"), MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
EXPECT_EQ(ERR_IO_PENDING,
trans.Start(&request, callback.callback(), NetLogWithSource()));
EXPECT_THAT(callback.WaitForResult(), IsOk());
std::string response_data;
EXPECT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ(CountWriteBytes(data_writes), trans.GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(data_reads), trans.GetTotalReceivedBytes());
}
TEST_F(HttpNetworkTransactionTest, TotalNetworkBytesPost100Continue) {
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(
std::make_unique<UploadBytesElementReader>("foo", 3));
ElementsUploadDataStream upload_data_stream(std::move(element_readers), 0);
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.foo.com/");
request.upload_data_stream = &upload_data_stream;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
MockWrite data_writes[] = {
MockWrite("POST / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 3\r\n\r\n"),
MockWrite("foo"),
};
MockRead data_reads[] = {
MockRead("HTTP/1.1 100 Continue\r\n\r\n"),
MockRead("HTTP/1.1 200 OK\r\n\r\n"), MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
EXPECT_EQ(ERR_IO_PENDING,
trans.Start(&request, callback.callback(), NetLogWithSource()));
EXPECT_THAT(callback.WaitForResult(), IsOk());
std::string response_data;
EXPECT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ(CountWriteBytes(data_writes), trans.GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(data_reads), trans.GetTotalReceivedBytes());
}
TEST_F(HttpNetworkTransactionTest, TotalNetworkBytesChunkedPost) {
ChunkedUploadDataStream upload_data_stream(0);
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("http://www.foo.com/");
request.upload_data_stream = &upload_data_stream;
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Send headers successfully, but get an error while sending the body.
MockWrite data_writes[] = {
MockWrite("POST / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n"
"Transfer-Encoding: chunked\r\n\r\n"),
MockWrite("1\r\nf\r\n"), MockWrite("2\r\noo\r\n"), MockWrite("0\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n\r\n"), MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
EXPECT_EQ(ERR_IO_PENDING,
trans.Start(&request, callback.callback(), NetLogWithSource()));
base::RunLoop().RunUntilIdle();
upload_data_stream.AppendData("f", 1, false);
base::RunLoop().RunUntilIdle();
upload_data_stream.AppendData("oo", 2, true);
EXPECT_THAT(callback.WaitForResult(), IsOk());
std::string response_data;
EXPECT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ(CountWriteBytes(data_writes), trans.GetTotalSentBytes());
EXPECT_EQ(CountReadBytes(data_reads), trans.GetTotalReceivedBytes());
}
void CheckContentEncodingMatching(SpdySessionDependencies* session_deps,
const std::string& accept_encoding,
const std::string& content_encoding,
const std::string& location,
bool should_match) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.foo.com/");
request.extra_headers.SetHeader(HttpRequestHeaders::kAcceptEncoding,
accept_encoding);
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(session_deps));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
// Send headers successfully, but get an error while sending the body.
MockWrite data_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.foo.com\r\n"
"Connection: keep-alive\r\n"
"Accept-Encoding: "),
MockWrite(accept_encoding.data()), MockWrite("\r\n\r\n"),
};
std::string response_code = "200 OK";
std::string extra;
if (!location.empty()) {
response_code = "301 Redirect\r\nLocation: ";
response_code.append(location);
}
MockRead data_reads[] = {
MockRead("HTTP/1.0 "),
MockRead(response_code.data()),
MockRead("\r\nContent-Encoding: "),
MockRead(content_encoding.data()),
MockRead("\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps->socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
if (should_match) {
EXPECT_THAT(rv, IsOk());
} else {
EXPECT_THAT(rv, IsError(ERR_CONTENT_DECODING_FAILED));
}
}
TEST_F(HttpNetworkTransactionTest, MatchContentEncoding1) {
CheckContentEncodingMatching(&session_deps_, "gzip,sdch", "br", "", false);
}
TEST_F(HttpNetworkTransactionTest, MatchContentEncoding2) {
CheckContentEncodingMatching(&session_deps_, "identity;q=1, *;q=0", "", "",
true);
}
TEST_F(HttpNetworkTransactionTest, MatchContentEncoding3) {
CheckContentEncodingMatching(&session_deps_, "identity;q=1, *;q=0", "gzip",
"", false);
}
TEST_F(HttpNetworkTransactionTest, MatchContentEncoding4) {
CheckContentEncodingMatching(&session_deps_, "identity;q=1, *;q=0", "gzip",
"www.foo.com/other", true);
}
TEST_F(HttpNetworkTransactionTest, ProxyResolutionFailsSync) {
ProxyConfig proxy_config;
proxy_config.set_pac_url(GURL("http://fooproxyurl"));
proxy_config.set_pac_mandatory(true);
MockAsyncProxyResolver resolver;
session_deps_.proxy_resolution_service.reset(new ProxyResolutionService(
std::make_unique<ProxyConfigServiceFixed>(ProxyConfigWithAnnotation(
proxy_config, TRAFFIC_ANNOTATION_FOR_TESTS)),
std::make_unique<FailingProxyResolverFactory>(), nullptr));
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(),
IsError(ERR_MANDATORY_PROXY_CONFIGURATION_FAILED));
}
TEST_F(HttpNetworkTransactionTest, ProxyResolutionFailsAsync) {
ProxyConfig proxy_config;
proxy_config.set_pac_url(GURL("http://fooproxyurl"));
proxy_config.set_pac_mandatory(true);
MockAsyncProxyResolverFactory* proxy_resolver_factory =
new MockAsyncProxyResolverFactory(false);
MockAsyncProxyResolver resolver;
session_deps_.proxy_resolution_service.reset(new ProxyResolutionService(
std::make_unique<ProxyConfigServiceFixed>(ProxyConfigWithAnnotation(
proxy_config, TRAFFIC_ANNOTATION_FOR_TESTS)),
base::WrapUnique(proxy_resolver_factory), nullptr));
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
proxy_resolver_factory->pending_requests()[0]->CompleteNowWithForwarder(
ERR_FAILED, &resolver);
EXPECT_THAT(callback.WaitForResult(),
IsError(ERR_MANDATORY_PROXY_CONFIGURATION_FAILED));
}
TEST_F(HttpNetworkTransactionTest, NoSupportedProxies) {
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"QUIC myproxy.org:443", TRAFFIC_ANNOTATION_FOR_TESTS);
session_deps_.enable_quic = false;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
TestCompletionCallback callback;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsError(ERR_NO_SUPPORTED_PROXIES));
}
//-----------------------------------------------------------------------------
// Reporting tests
#if BUILDFLAG(ENABLE_REPORTING)
class HttpNetworkTransactionReportingTest : public HttpNetworkTransactionTest {
protected:
void SetUp() override {
HttpNetworkTransactionTest::SetUp();
auto test_reporting_context = std::make_unique<TestReportingContext>(
&clock_, &tick_clock_, ReportingPolicy());
test_reporting_context_ = test_reporting_context.get();
session_deps_.reporting_service =
ReportingService::CreateForTesting(std::move(test_reporting_context));
}
TestReportingContext* reporting_context() const {
return test_reporting_context_;
}
void clear_reporting_service() {
session_deps_.reporting_service.reset();
test_reporting_context_ = nullptr;
}
// Makes an HTTPS request that should install a valid Reporting policy.
void RequestPolicy(CertStatus cert_status = 0) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL(url_);
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Report-To: {\"group\": \"nel\", \"max_age\": 86400, "
"\"endpoints\": [{\"url\": "
"\"https://www.example.org/upload/\"}]}\r\n"),
MockRead("\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider reads(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&reads);
SSLSocketDataProvider ssl(ASYNC, OK);
if (request.url.SchemeIsCryptographic()) {
ssl.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "wildcard.pem");
ASSERT_TRUE(ssl.ssl_info.cert);
ssl.ssl_info.cert_status = cert_status;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
}
TestCompletionCallback callback;
auto session = CreateSession(&session_deps_);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
}
protected:
std::string url_ = "https://www.example.org/";
private:
TestReportingContext* test_reporting_context_;
};
TEST_F(HttpNetworkTransactionReportingTest,
DontProcessReportToHeaderNoService) {
base::HistogramTester histograms;
clear_reporting_service();
RequestPolicy();
histograms.ExpectBucketCount(
ReportingHeaderParser::kHeaderOutcomeHistogram,
ReportingHeaderParser::HeaderOutcome::DISCARDED_NO_REPORTING_SERVICE, 1);
}
TEST_F(HttpNetworkTransactionReportingTest, DontProcessReportToHeaderHttp) {
base::HistogramTester histograms;
url_ = "http://www.example.org/";
RequestPolicy();
histograms.ExpectBucketCount(
ReportingHeaderParser::kHeaderOutcomeHistogram,
ReportingHeaderParser::HeaderOutcome::DISCARDED_INVALID_SSL_INFO, 1);
}
TEST_F(HttpNetworkTransactionReportingTest, ProcessReportToHeaderHttps) {
RequestPolicy();
ASSERT_EQ(1u, reporting_context()->cache()->GetEndpointCount());
const ReportingClient endpoint =
reporting_context()->cache()->GetEndpointForTesting(
url::Origin::Create(GURL("https://www.example.org/")), "nel",
GURL("https://www.example.org/upload/"));
EXPECT_TRUE(endpoint);
}
TEST_F(HttpNetworkTransactionReportingTest,
DontProcessReportToHeaderInvalidHttps) {
base::HistogramTester histograms;
CertStatus cert_status = CERT_STATUS_COMMON_NAME_INVALID;
RequestPolicy(cert_status);
histograms.ExpectBucketCount(
ReportingHeaderParser::kHeaderOutcomeHistogram,
ReportingHeaderParser::HeaderOutcome::DISCARDED_CERT_STATUS_ERROR, 1);
}
#endif // BUILDFLAG(ENABLE_REPORTING)
//-----------------------------------------------------------------------------
// Network Error Logging tests
#if BUILDFLAG(ENABLE_REPORTING)
namespace {
const char kUserAgent[] = "Mozilla/1.0";
const char kReferrer[] = "https://www.referrer.org/";
} // namespace
class HttpNetworkTransactionNetworkErrorLoggingTest
: public HttpNetworkTransactionTest {
protected:
void SetUp() override {
HttpNetworkTransactionTest::SetUp();
auto network_error_logging_service =
std::make_unique<TestNetworkErrorLoggingService>();
test_network_error_logging_service_ = network_error_logging_service.get();
session_deps_.network_error_logging_service =
std::move(network_error_logging_service);
extra_headers_.SetHeader("User-Agent", kUserAgent);
extra_headers_.SetHeader("Referer", kReferrer);
request_.method = "GET";
request_.url = GURL(url_);
request_.extra_headers = extra_headers_;
request_.reporting_upload_depth = reporting_upload_depth_;
request_.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
}
TestNetworkErrorLoggingService* network_error_logging_service() const {
return test_network_error_logging_service_;
}
void clear_network_error_logging_service() {
session_deps_.network_error_logging_service.reset();
test_network_error_logging_service_ = nullptr;
}
// Makes an HTTPS request that should install a valid NEL policy.
void RequestPolicy(CertStatus cert_status = 0) {
std::string extra_header_string = extra_headers_.ToString();
MockWrite data_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"),
MockWrite(ASYNC, extra_header_string.data(),
extra_header_string.size()),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("NEL: {\"report_to\": \"nel\", \"max_age\": 86400}\r\n"),
MockRead("\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider reads(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&reads);
SSLSocketDataProvider ssl(ASYNC, OK);
if (request_.url.SchemeIsCryptographic()) {
ssl.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "wildcard.pem");
ASSERT_TRUE(ssl.ssl_info.cert);
ssl.ssl_info.cert_status = cert_status;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
}
TestCompletionCallback callback;
auto session = CreateSession(&session_deps_);
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request_, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
std::string response_data;
ASSERT_THAT(ReadTransaction(&trans, &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
}
void CheckReport(size_t index,
int status_code,
int error_type,
IPAddress server_ip = IPAddress::IPv4Localhost()) {
ASSERT_LT(index, network_error_logging_service()->errors().size());
const NetworkErrorLoggingService::RequestDetails& error =
network_error_logging_service()->errors()[index];
EXPECT_EQ(url_, error.uri);
EXPECT_EQ(kReferrer, error.referrer);
EXPECT_EQ(kUserAgent, error.user_agent);
EXPECT_EQ(server_ip, error.server_ip);
EXPECT_EQ("http/1.1", error.protocol);
EXPECT_EQ("GET", error.method);
EXPECT_EQ(status_code, error.status_code);
EXPECT_EQ(error_type, error.type);
EXPECT_EQ(0, error.reporting_upload_depth);
}
protected:
std::string url_ = "https://www.example.org/";
CertStatus cert_status_ = 0;
HttpRequestInfo request_;
HttpRequestHeaders extra_headers_;
int reporting_upload_depth_ = 0;
private:
TestNetworkErrorLoggingService* test_network_error_logging_service_;
};
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
DontProcessNelHeaderNoService) {
base::HistogramTester histograms;
clear_network_error_logging_service();
RequestPolicy();
histograms.ExpectBucketCount(
NetworkErrorLoggingService::kHeaderOutcomeHistogram,
NetworkErrorLoggingService::HeaderOutcome::
DISCARDED_NO_NETWORK_ERROR_LOGGING_SERVICE,
1);
}
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
DontProcessNelHeaderHttp) {
base::HistogramTester histograms;
url_ = "http://www.example.org/";
request_.url = GURL(url_);
RequestPolicy();
histograms.ExpectBucketCount(
NetworkErrorLoggingService::kHeaderOutcomeHistogram,
NetworkErrorLoggingService::HeaderOutcome::DISCARDED_INVALID_SSL_INFO, 1);
}
// Don't set NEL policies received on a proxied connection.
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
DontProcessNelHeaderProxy) {
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
BoundTestNetLog log;
session_deps_.net_log = log.bound().net_log();
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("NEL: {\"report_to\": \"nel\", \"max_age\": 86400}\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 100\r\n\r\n"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
SSLSocketDataProvider ssl(ASYNC, OK);
ssl.ssl_info.cert =
ImportCertFromFile(GetTestCertsDirectory(), "wildcard.pem");
ASSERT_TRUE(ssl.ssl_info.cert);
ssl.ssl_info.cert_status = 0;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback1;
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
int rv = trans.Start(&request, callback1.callback(), log.bound());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback1.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans.GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_EQ(200, response->headers->response_code());
EXPECT_TRUE(response->was_fetched_via_proxy);
// No NEL header was set.
EXPECT_EQ(0u, network_error_logging_service()->headers().size());
}
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest, ProcessNelHeaderHttps) {
RequestPolicy();
ASSERT_EQ(1u, network_error_logging_service()->headers().size());
const auto& header = network_error_logging_service()->headers()[0];
EXPECT_EQ(url::Origin::Create(GURL("https://www.example.org/")),
header.origin);
EXPECT_EQ(IPAddress::IPv4Localhost(), header.received_ip_address);
EXPECT_EQ("{\"report_to\": \"nel\", \"max_age\": 86400}", header.value);
}
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
DontProcessNelHeaderInvalidHttps) {
base::HistogramTester histograms;
CertStatus cert_status = CERT_STATUS_COMMON_NAME_INVALID;
RequestPolicy(cert_status);
histograms.ExpectBucketCount(
NetworkErrorLoggingService::kHeaderOutcomeHistogram,
NetworkErrorLoggingService::HeaderOutcome::DISCARDED_CERT_STATUS_ERROR,
1);
}
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest, CreateReportSuccess) {
RequestPolicy();
ASSERT_EQ(1u, network_error_logging_service()->errors().size());
CheckReport(0 /* index */, 200 /* status_code */, OK);
}
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
CreateReportErrorAfterStart) {
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
MockConnect mock_connect(SYNCHRONOUS, ERR_NAME_NOT_RESOLVED);
StaticSocketDataProvider data;
data.set_connect_data(mock_connect);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans->Start(&request_, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsError(ERR_NAME_NOT_RESOLVED));
trans.reset();
ASSERT_EQ(1u, network_error_logging_service()->errors().size());
CheckReport(0 /* index */, 0 /* status_code */, ERR_NAME_NOT_RESOLVED,
IPAddress() /* server_ip */);
}
// Same as above except the error is ASYNC
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
CreateReportErrorAfterStartAsync) {
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
MockConnect mock_connect(ASYNC, ERR_NAME_NOT_RESOLVED);
StaticSocketDataProvider data;
data.set_connect_data(mock_connect);
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
int rv = trans->Start(&request_, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsError(ERR_NAME_NOT_RESOLVED));
trans.reset();
ASSERT_EQ(1u, network_error_logging_service()->errors().size());
CheckReport(0 /* index */, 0 /* status_code */, ERR_NAME_NOT_RESOLVED,
IPAddress() /* server_ip */);
}
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
CreateReportReadBodyError) {
std::string extra_header_string = extra_headers_.ToString();
MockWrite data_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"),
MockWrite(ASYNC, extra_header_string.data(), extra_header_string.size()),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Length: 100\r\n\r\n"), // wrong content length
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider reads(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&reads);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
// Log start time
base::TimeTicks start_time = base::TimeTicks::Now();
TestCompletionCallback callback;
auto session = CreateSession(&session_deps_);
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request_, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.0 200 OK", response->headers->GetStatusLine());
std::string response_data;
rv = ReadTransaction(trans.get(), &response_data);
EXPECT_THAT(rv, IsError(ERR_CONTENT_LENGTH_MISMATCH));
trans.reset();
ASSERT_EQ(1u, network_error_logging_service()->errors().size());
CheckReport(0 /* index */, 200 /* status_code */,
ERR_CONTENT_LENGTH_MISMATCH);
const NetworkErrorLoggingService::RequestDetails& error =
network_error_logging_service()->errors()[0];
EXPECT_LE(error.elapsed_time, base::TimeTicks::Now() - start_time);
}
// Same as above except the final read is ASYNC.
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
CreateReportReadBodyErrorAsync) {
std::string extra_header_string = extra_headers_.ToString();
MockWrite data_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"),
MockWrite(ASYNC, extra_header_string.data(), extra_header_string.size()),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Length: 100\r\n\r\n"), // wrong content length
MockRead("hello world"),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider reads(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&reads);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
// Log start time
base::TimeTicks start_time = base::TimeTicks::Now();
TestCompletionCallback callback;
auto session = CreateSession(&session_deps_);
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request_, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.0 200 OK", response->headers->GetStatusLine());
std::string response_data;
rv = ReadTransaction(trans.get(), &response_data);
EXPECT_THAT(rv, IsError(ERR_CONTENT_LENGTH_MISMATCH));
trans.reset();
ASSERT_EQ(1u, network_error_logging_service()->errors().size());
CheckReport(0 /* index */, 200 /* status_code */,
ERR_CONTENT_LENGTH_MISMATCH);
const NetworkErrorLoggingService::RequestDetails& error =
network_error_logging_service()->errors()[0];
EXPECT_LE(error.elapsed_time, base::TimeTicks::Now() - start_time);
}
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
CreateReportRestartWithAuth) {
std::string extra_header_string = extra_headers_.ToString();
static const base::TimeDelta kSleepDuration =
base::TimeDelta::FromMilliseconds(10);
MockWrite data_writes1[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"),
MockWrite(ASYNC, extra_header_string.data(), extra_header_string.size()),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
// Give a couple authenticate options (only the middle one is actually
// supported).
MockRead("WWW-Authenticate: Basic invalid\r\n"), // Malformed.
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("WWW-Authenticate: UNSUPPORTED realm=\"FOO\"\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
// Large content-length -- won't matter, as connection will be reset.
MockRead("Content-Length: 10000\r\n\r\n"),
MockRead(SYNCHRONOUS, ERR_FAILED),
};
// After calling trans->RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite data_writes2[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJhcg==\r\n"),
MockWrite(ASYNC, extra_header_string.data(), extra_header_string.size()),
};
// Lastly, the server responds with the actual content.
MockRead data_reads2[] = {
MockRead("HTTP/1.0 200 OK\r\n\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
SSLSocketDataProvider ssl1(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
SSLSocketDataProvider ssl2(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
base::TimeTicks start_time = base::TimeTicks::Now();
base::TimeTicks restart_time;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback1;
int rv = trans->Start(&request_, callback1.callback(), NetLogWithSource());
EXPECT_THAT(callback1.GetResult(rv), IsOk());
ASSERT_EQ(1u, network_error_logging_service()->errors().size());
TestCompletionCallback callback2;
// Wait 10 ms then restart with auth
FastForwardBy(kSleepDuration);
restart_time = base::TimeTicks::Now();
rv =
trans->RestartWithAuth(AuthCredentials(kFoo, kBar), callback2.callback());
EXPECT_THAT(callback2.GetResult(rv), IsOk());
std::string response_data;
ASSERT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
trans.reset();
// One 401 report for the auth challenge, then a 200 report for the successful
// retry. Note that we don't report the error draining the body, as the first
// request already generated a report for the auth challenge.
ASSERT_EQ(2u, network_error_logging_service()->errors().size());
// Check error report contents
CheckReport(0 /* index */, 401 /* status_code */, OK);
CheckReport(1 /* index */, 200 /* status_code */, OK);
const NetworkErrorLoggingService::RequestDetails& error1 =
network_error_logging_service()->errors()[0];
const NetworkErrorLoggingService::RequestDetails& error2 =
network_error_logging_service()->errors()[1];
// Sanity-check elapsed time values
EXPECT_EQ(error1.elapsed_time, restart_time - start_time - kSleepDuration);
// Check that the start time is refreshed when restarting with auth.
EXPECT_EQ(error2.elapsed_time, base::TimeTicks::Now() - restart_time);
}
// Same as above, except draining the body before restarting fails
// asynchronously.
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
CreateReportRestartWithAuthAsync) {
std::string extra_header_string = extra_headers_.ToString();
static const base::TimeDelta kSleepDuration =
base::TimeDelta::FromMilliseconds(10);
MockWrite data_writes1[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"),
MockWrite(ASYNC, extra_header_string.data(), extra_header_string.size()),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.0 401 Unauthorized\r\n"),
// Give a couple authenticate options (only the middle one is actually
// supported).
MockRead("WWW-Authenticate: Basic invalid\r\n"), // Malformed.
MockRead("WWW-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("WWW-Authenticate: UNSUPPORTED realm=\"FOO\"\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
// Large content-length -- won't matter, as connection will be reset.
MockRead("Content-Length: 10000\r\n\r\n"),
MockRead(ASYNC, ERR_FAILED),
};
// After calling trans->RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite data_writes2[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Authorization: Basic Zm9vOmJhcg==\r\n"),
MockWrite(ASYNC, extra_header_string.data(), extra_header_string.size()),
};
// Lastly, the server responds with the actual content.
MockRead data_reads2[] = {
MockRead("HTTP/1.0 200 OK\r\n\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
SSLSocketDataProvider ssl1(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
SSLSocketDataProvider ssl2(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
base::TimeTicks start_time = base::TimeTicks::Now();
base::TimeTicks restart_time;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback1;
int rv = trans->Start(&request_, callback1.callback(), NetLogWithSource());
EXPECT_THAT(callback1.GetResult(rv), IsOk());
ASSERT_EQ(1u, network_error_logging_service()->errors().size());
TestCompletionCallback callback2;
// Wait 10 ms then restart with auth
FastForwardBy(kSleepDuration);
restart_time = base::TimeTicks::Now();
rv =
trans->RestartWithAuth(AuthCredentials(kFoo, kBar), callback2.callback());
EXPECT_THAT(callback2.GetResult(rv), IsOk());
std::string response_data;
ASSERT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
trans.reset();
// One 401 report for the auth challenge, then a 200 report for the successful
// retry. Note that we don't report the error draining the body, as the first
// request already generated a report for the auth challenge.
ASSERT_EQ(2u, network_error_logging_service()->errors().size());
// Check error report contents
CheckReport(0 /* index */, 401 /* status_code */, OK);
CheckReport(1 /* index */, 200 /* status_code */, OK);
const NetworkErrorLoggingService::RequestDetails& error1 =
network_error_logging_service()->errors()[0];
const NetworkErrorLoggingService::RequestDetails& error2 =
network_error_logging_service()->errors()[1];
// Sanity-check elapsed time values
EXPECT_EQ(error1.elapsed_time, restart_time - start_time - kSleepDuration);
// Check that the start time is refreshed when restarting with auth.
EXPECT_EQ(error2.elapsed_time, base::TimeTicks::Now() - restart_time);
}
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
CreateReportRetryKeepAliveConnectionReset) {
std::string extra_header_string = extra_headers_.ToString();
MockWrite data_writes1[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"),
MockWrite(ASYNC, extra_header_string.data(), extra_header_string.size()),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"),
MockWrite(ASYNC, extra_header_string.data(), extra_header_string.size()),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
MockRead("hello"),
// Connection is reset
MockRead(ASYNC, ERR_CONNECTION_RESET),
};
// Successful retry
MockRead data_reads2[] = {
MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
MockRead("world"),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
SSLSocketDataProvider ssl1(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
SSLSocketDataProvider ssl2(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans1 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback1;
int rv = trans1->Start(&request_, callback1.callback(), NetLogWithSource());
EXPECT_THAT(callback1.GetResult(rv), IsOk());
std::string response_data;
ASSERT_THAT(ReadTransaction(trans1.get(), &response_data), IsOk());
EXPECT_EQ("hello", response_data);
ASSERT_EQ(1u, network_error_logging_service()->errors().size());
auto trans2 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback2;
rv = trans2->Start(&request_, callback2.callback(), NetLogWithSource());
EXPECT_THAT(callback2.GetResult(rv), IsOk());
ASSERT_THAT(ReadTransaction(trans2.get(), &response_data), IsOk());
EXPECT_EQ("world", response_data);
trans1.reset();
trans2.reset();
// One OK report from first request, then a ERR_CONNECTION_RESET report from
// the second request, then an OK report from the successful retry.
ASSERT_EQ(3u, network_error_logging_service()->errors().size());
// Check error report contents
CheckReport(0 /* index */, 200 /* status_code */, OK);
CheckReport(1 /* index */, 0 /* status_code */, ERR_CONNECTION_RESET);
CheckReport(2 /* index */, 200 /* status_code */, OK);
}
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
CreateReportRetryKeepAlive408) {
std::string extra_header_string = extra_headers_.ToString();
MockWrite data_writes1[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"),
MockWrite(ASYNC, extra_header_string.data(), extra_header_string.size()),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"),
MockWrite(ASYNC, extra_header_string.data(), extra_header_string.size()),
};
MockRead data_reads1[] = {
MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
MockRead("hello"),
// 408 Request Timeout
MockRead(SYNCHRONOUS,
"HTTP/1.1 408 Request Timeout\r\n"
"Connection: Keep-Alive\r\n"
"Content-Length: 6\r\n\r\n"
"Pickle"),
};
// Successful retry
MockRead data_reads2[] = {
MockRead("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
MockRead("world"),
MockRead(ASYNC, OK),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
StaticSocketDataProvider data2(data_reads2, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data1);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
SSLSocketDataProvider ssl1(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl1);
SSLSocketDataProvider ssl2(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl2);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans1 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback1;
int rv = trans1->Start(&request_, callback1.callback(), NetLogWithSource());
EXPECT_THAT(callback1.GetResult(rv), IsOk());
std::string response_data;
ASSERT_THAT(ReadTransaction(trans1.get(), &response_data), IsOk());
EXPECT_EQ("hello", response_data);
ASSERT_EQ(1u, network_error_logging_service()->errors().size());
auto trans2 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback2;
rv = trans2->Start(&request_, callback2.callback(), NetLogWithSource());
EXPECT_THAT(callback2.GetResult(rv), IsOk());
ASSERT_THAT(ReadTransaction(trans2.get(), &response_data), IsOk());
EXPECT_EQ("world", response_data);
trans1.reset();
trans2.reset();
// One 200 report from first request, then a 408 report from
// the second request, then a 200 report from the successful retry.
ASSERT_EQ(3u, network_error_logging_service()->errors().size());
// Check error report contents
CheckReport(0 /* index */, 200 /* status_code */, OK);
CheckReport(1 /* index */, 408 /* status_code */, OK);
CheckReport(2 /* index */, 200 /* status_code */, OK);
}
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
CreateReportRetry421WithoutConnectionPooling) {
// Two hosts resolve to the same IP address.
const std::string ip_addr = "1.2.3.4";
IPAddress ip;
ASSERT_TRUE(ip.AssignFromIPLiteral(ip_addr));
IPEndPoint peer_addr = IPEndPoint(ip, 443);
session_deps_.host_resolver = std::make_unique<MockCachingHostResolver>();
session_deps_.host_resolver->rules()->AddRule("www.example.org", ip_addr);
session_deps_.host_resolver->rules()->AddRule("mail.example.org", ip_addr);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Two requests on the first connection.
spdy::SpdySerializedFrame req1(
spdy_util_.ConstructSpdyGet("https://www.example.org", 1, LOWEST));
spdy_util_.UpdateWithStreamDestruction(1);
spdy::SpdySerializedFrame req2(
spdy_util_.ConstructSpdyGet("https://mail.example.org", 3, LOWEST));
spdy::SpdySerializedFrame rst(
spdy_util_.ConstructSpdyRstStream(3, spdy::ERROR_CODE_CANCEL));
MockWrite writes1[] = {
CreateMockWrite(req1, 0),
CreateMockWrite(req2, 3),
CreateMockWrite(rst, 6),
};
// The first one succeeds, the second gets error 421 Misdirected Request.
spdy::SpdySerializedFrame resp1(
spdy_util_.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame body1(spdy_util_.ConstructSpdyDataFrame(1, true));
spdy::SpdyHeaderBlock response_headers;
response_headers[spdy::kHttp2StatusHeader] = "421";
spdy::SpdySerializedFrame resp2(
spdy_util_.ConstructSpdyReply(3, std::move(response_headers)));
MockRead reads1[] = {CreateMockRead(resp1, 1), CreateMockRead(body1, 2),
CreateMockRead(resp2, 4), MockRead(ASYNC, 0, 5)};
MockConnect connect1(ASYNC, OK, peer_addr);
SequencedSocketData data1(connect1, reads1, writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
AddSSLSocketData();
// Retry the second request on a second connection.
SpdyTestUtil spdy_util2;
spdy::SpdySerializedFrame req3(
spdy_util2.ConstructSpdyGet("https://mail.example.org", 1, LOWEST));
MockWrite writes2[] = {
CreateMockWrite(req3, 0),
};
spdy::SpdySerializedFrame resp3(
spdy_util2.ConstructSpdyGetReply(nullptr, 0, 1));
spdy::SpdySerializedFrame body3(spdy_util2.ConstructSpdyDataFrame(1, true));
MockRead reads2[] = {CreateMockRead(resp3, 1), CreateMockRead(body3, 2),
MockRead(ASYNC, 0, 3)};
MockConnect connect2(ASYNC, OK, peer_addr);
SequencedSocketData data2(connect2, reads2, writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
AddSSLSocketData();
// Preload mail.example.org into HostCache.
int rv = session_deps_.host_resolver->LoadIntoCache(
HostPortPair("mail.example.com", 443), base::nullopt);
EXPECT_THAT(rv, IsOk());
HttpRequestInfo request1;
request1.method = "GET";
request1.url = GURL("https://www.example.org/");
request1.load_flags = 0;
request1.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
auto trans1 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
rv = trans1->Start(&request1, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans1->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
std::string response_data;
ASSERT_THAT(ReadTransaction(trans1.get(), &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
trans1.reset();
ASSERT_EQ(1u, network_error_logging_service()->errors().size());
HttpRequestInfo request2;
request2.method = "GET";
request2.url = GURL("https://mail.example.org/");
request2.load_flags = 0;
request2.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
auto trans2 =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
BoundTestNetLog log;
rv = trans2->Start(&request2, callback.callback(), log.bound());
EXPECT_THAT(callback.GetResult(rv), IsOk());
response = trans2->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.1 200", response->headers->GetStatusLine());
EXPECT_TRUE(response->was_fetched_via_spdy);
EXPECT_TRUE(response->was_alpn_negotiated);
ASSERT_THAT(ReadTransaction(trans2.get(), &response_data), IsOk());
EXPECT_EQ("hello!", response_data);
trans2.reset();
// One 200 report from the first request, then a 421 report from the
// second request, then a 200 report from the successful retry.
ASSERT_EQ(3u, network_error_logging_service()->errors().size());
// Check error report contents
const NetworkErrorLoggingService::RequestDetails& error1 =
network_error_logging_service()->errors()[0];
EXPECT_EQ(GURL("https://www.example.org/"), error1.uri);
EXPECT_TRUE(error1.referrer.is_empty());
EXPECT_EQ("", error1.user_agent);
EXPECT_EQ(ip, error1.server_ip);
EXPECT_EQ("h2", error1.protocol);
EXPECT_EQ("GET", error1.method);
EXPECT_EQ(200, error1.status_code);
EXPECT_EQ(OK, error1.type);
EXPECT_EQ(0, error1.reporting_upload_depth);
const NetworkErrorLoggingService::RequestDetails& error2 =
network_error_logging_service()->errors()[1];
EXPECT_EQ(GURL("https://mail.example.org/"), error2.uri);
EXPECT_TRUE(error2.referrer.is_empty());
EXPECT_EQ("", error2.user_agent);
EXPECT_EQ(ip, error2.server_ip);
EXPECT_EQ("h2", error2.protocol);
EXPECT_EQ("GET", error2.method);
EXPECT_EQ(421, error2.status_code);
EXPECT_EQ(OK, error2.type);
EXPECT_EQ(0, error2.reporting_upload_depth);
const NetworkErrorLoggingService::RequestDetails& error3 =
network_error_logging_service()->errors()[2];
EXPECT_EQ(GURL("https://mail.example.org/"), error3.uri);
EXPECT_TRUE(error3.referrer.is_empty());
EXPECT_EQ("", error3.user_agent);
EXPECT_EQ(ip, error3.server_ip);
EXPECT_EQ("h2", error3.protocol);
EXPECT_EQ("GET", error3.method);
EXPECT_EQ(200, error3.status_code);
EXPECT_EQ(OK, error3.type);
EXPECT_EQ(0, error3.reporting_upload_depth);
}
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
CreateReportCancelAfterStart) {
StaticSocketDataProvider data;
data.set_connect_data(MockConnect(SYNCHRONOUS, ERR_IO_PENDING));
session_deps_.socket_factory->AddSocketDataProvider(&data);
TestCompletionCallback callback;
auto session = CreateSession(&session_deps_);
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request_, callback.callback(), NetLogWithSource());
EXPECT_EQ(rv, ERR_IO_PENDING);
// Cancel after start.
trans.reset();
ASSERT_EQ(1u, network_error_logging_service()->errors().size());
CheckReport(0 /* index */, 0 /* status_code */, ERR_ABORTED,
IPAddress() /* server_ip */);
}
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
CreateReportCancelBeforeReadingBody) {
std::string extra_header_string = extra_headers_.ToString();
MockWrite data_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"),
MockWrite(ASYNC, extra_header_string.data(), extra_header_string.size()),
};
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Length: 100\r\n\r\n"), // Body is never read.
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback;
auto session = CreateSession(&session_deps_);
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request_, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
EXPECT_TRUE(response->headers);
EXPECT_EQ("HTTP/1.0 200 OK", response->headers->GetStatusLine());
// Cancel before reading the body.
trans.reset();
ASSERT_EQ(1u, network_error_logging_service()->errors().size());
CheckReport(0 /* index */, 200 /* status_code */, ERR_ABORTED);
}
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest, DontCreateReportHttp) {
base::HistogramTester histograms;
RequestPolicy();
EXPECT_EQ(1u, network_error_logging_service()->headers().size());
EXPECT_EQ(1u, network_error_logging_service()->errors().size());
// Make HTTP request
std::string extra_header_string = extra_headers_.ToString();
MockRead data_reads[] = {
MockRead("HTTP/1.0 200 OK\r\n\r\n"),
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
MockWrite data_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"),
MockWrite(ASYNC, extra_header_string.data(), extra_header_string.size()),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
// Insecure url
url_ = "http://www.example.org/";
request_.url = GURL(url_);
TestCompletionCallback callback;
auto session = CreateSession(&session_deps_);
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request_, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsOk());
std::string response_data;
ASSERT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
// Insecure request does not generate a report
histograms.ExpectBucketCount(
NetworkErrorLoggingService::kRequestOutcomeHistogram,
NetworkErrorLoggingService::RequestOutcome::kDiscardedInsecureOrigin, 1);
EXPECT_EQ(1u, network_error_logging_service()->errors().size());
}
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
DontCreateReportHttpError) {
base::HistogramTester histograms;
RequestPolicy();
EXPECT_EQ(1u, network_error_logging_service()->headers().size());
EXPECT_EQ(1u, network_error_logging_service()->errors().size());
// Make HTTP request that fails
MockRead data_reads[] = {
MockRead("hello world"),
MockRead(SYNCHRONOUS, OK),
};
StaticSocketDataProvider data(data_reads, base::span<MockWrite>());
session_deps_.socket_factory->AddSocketDataProvider(&data);
url_ = "http://www.originwithoutpolicy.com:2000/";
request_.url = GURL(url_);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans->Start(&request_, callback.callback(), NetLogWithSource());
EXPECT_THAT(callback.GetResult(rv), IsError(ERR_INVALID_HTTP_RESPONSE));
// Insecure request does not generate a report, regardless of existence of a
// policy for the origin.
histograms.ExpectBucketCount(
NetworkErrorLoggingService::kRequestOutcomeHistogram,
NetworkErrorLoggingService::RequestOutcome::kDiscardedInsecureOrigin, 1);
EXPECT_EQ(1u, network_error_logging_service()->errors().size());
}
// Don't report on proxy auth challenges, don't report if connecting through a
// proxy.
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest, DontCreateReportProxy) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
// Configure against proxy server "myproxy:70".
session_deps_.proxy_resolution_service =
ProxyResolutionService::CreateFixedFromPacResult(
"PROXY myproxy:70", TRAFFIC_ANNOTATION_FOR_TESTS);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
// Since we have proxy, should try to establish tunnel.
MockWrite data_writes1[] = {
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a non-persistent
// connection.
MockRead data_reads1[] = {
// No credentials.
MockRead("HTTP/1.1 407 Proxy Authentication Required\r\n"),
MockRead("Proxy-Authenticate: Basic realm=\"MyRealm1\"\r\n"),
MockRead("Proxy-Connection: close\r\n\r\n"),
};
MockWrite data_writes2[] = {
// After calling trans->RestartWithAuth(), this is the request we should
// be issuing -- the final header line contains the credentials.
MockWrite("CONNECT www.example.org:443 HTTP/1.1\r\n"
"Host: www.example.org:443\r\n"
"Proxy-Connection: keep-alive\r\n"
"Proxy-Authorization: Basic Zm9vOmJhcg==\r\n\r\n"),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
MockRead data_reads2[] = {
MockRead("HTTP/1.1 200 Connection Established\r\n\r\n"),
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n"),
MockRead("Content-Length: 5\r\n\r\n"),
MockRead(SYNCHRONOUS, "hello"),
};
StaticSocketDataProvider data1(data_reads1, data_writes1);
session_deps_.socket_factory->AddSocketDataProvider(&data1);
StaticSocketDataProvider data2(data_reads2, data_writes2);
session_deps_.socket_factory->AddSocketDataProvider(&data2);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
TestCompletionCallback callback1;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(callback1.GetResult(rv), IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
EXPECT_EQ(407, response->headers->response_code());
std::string response_data;
rv = ReadTransaction(trans.get(), &response_data);
EXPECT_THAT(rv, IsError(ERR_TUNNEL_CONNECTION_FAILED));
// No NEL report is generated for the 407.
EXPECT_EQ(0u, network_error_logging_service()->errors().size());
TestCompletionCallback callback2;
rv =
trans->RestartWithAuth(AuthCredentials(kFoo, kBar), callback2.callback());
EXPECT_THAT(callback2.GetResult(rv), IsOk());
response = trans->GetResponseInfo();
EXPECT_EQ(200, response->headers->response_code());
ASSERT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ("hello", response_data);
trans.reset();
// No NEL report is generated because we are behind a proxy.
EXPECT_EQ(0u, network_error_logging_service()->errors().size());
}
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest,
ReportContainsUploadDepth) {
reporting_upload_depth_ = 7;
request_.reporting_upload_depth = reporting_upload_depth_;
RequestPolicy();
ASSERT_EQ(1u, network_error_logging_service()->errors().size());
const NetworkErrorLoggingService::RequestDetails& error =
network_error_logging_service()->errors()[0];
EXPECT_EQ(7, error.reporting_upload_depth);
}
TEST_F(HttpNetworkTransactionNetworkErrorLoggingTest, ReportElapsedTime) {
std::string extra_header_string = extra_headers_.ToString();
static const base::TimeDelta kSleepDuration =
base::TimeDelta::FromMilliseconds(10);
std::vector<MockWrite> data_writes = {
MockWrite(ASYNC, 0,
"GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"),
MockWrite(ASYNC, 1, extra_header_string.data()),
};
std::vector<MockRead> data_reads = {
// Write one byte of the status line, followed by a pause.
MockRead(ASYNC, 2, "H"),
MockRead(ASYNC, ERR_IO_PENDING, 3),
MockRead(ASYNC, 4, "TTP/1.1 200 OK\r\n\r\n"),
MockRead(ASYNC, 5, "hello world"),
MockRead(SYNCHRONOUS, OK, 6),
};
SequencedSocketData data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(ASYNC, OK);
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback;
int rv = trans->Start(&request_, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
data.RunUntilPaused();
ASSERT_TRUE(data.IsPaused());
FastForwardBy(kSleepDuration);
data.Resume();
EXPECT_THAT(callback.GetResult(rv), IsOk());
std::string response_data;
ASSERT_THAT(ReadTransaction(trans.get(), &response_data), IsOk());
EXPECT_EQ("hello world", response_data);
trans.reset();
ASSERT_EQ(1u, network_error_logging_service()->errors().size());
CheckReport(0 /* index */, 200 /* status_code */, OK);
const NetworkErrorLoggingService::RequestDetails& error =
network_error_logging_service()->errors()[0];
// Sanity-check elapsed time in error report
EXPECT_EQ(kSleepDuration, error.elapsed_time);
}
#endif // BUILDFLAG(ENABLE_REPORTING)
TEST_F(HttpNetworkTransactionTest, AlwaysFailRequestToCache) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("http://example.org/");
request.load_flags = LOAD_ONLY_FROM_CACHE;
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get());
TestCompletionCallback callback1;
int rv = trans.Start(&request, callback1.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_CACHE_MISS));
}
TEST_F(HttpNetworkTransactionTest, ZeroRTTDoesntConfirm) {
HttpRequestInfo request;
request.method = "GET";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a persistent
// connection.
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 1\r\n\r\n"),
MockRead(SYNCHRONOUS, "1"),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(SYNCHRONOUS, OK);
ssl.confirm = MockConfirm(SYNCHRONOUS, OK);
session_deps_.enable_early_data = true;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
TestCompletionCallback callback;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(1, response->headers->GetContentLength());
// Check that ConfirmHandshake wasn't called.
ASSERT_FALSE(ssl.ConfirmDataConsumed());
ASSERT_TRUE(ssl.WriteBeforeConfirm());
trans.reset();
session->CloseAllConnections();
}
TEST_F(HttpNetworkTransactionTest, ZeroRTTSyncConfirmSyncWrite) {
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite(SYNCHRONOUS,
"POST / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 0\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a persistent
// connection.
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 1\r\n\r\n"),
MockRead(SYNCHRONOUS, "1"),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(SYNCHRONOUS, OK);
ssl.confirm = MockConfirm(SYNCHRONOUS, OK);
session_deps_.enable_early_data = true;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
TestCompletionCallback callback;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(1, response->headers->GetContentLength());
// Check that the Write didn't get called before ConfirmHandshake completed.
ASSERT_FALSE(ssl.WriteBeforeConfirm());
trans.reset();
session->CloseAllConnections();
}
TEST_F(HttpNetworkTransactionTest, ZeroRTTSyncConfirmAsyncWrite) {
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite(ASYNC,
"POST / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 0\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a persistent
// connection.
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 1\r\n\r\n"),
MockRead(SYNCHRONOUS, "1"),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(SYNCHRONOUS, OK);
ssl.confirm = MockConfirm(SYNCHRONOUS, OK);
session_deps_.enable_early_data = true;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
TestCompletionCallback callback;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(1, response->headers->GetContentLength());
// Check that the Write didn't get called before ConfirmHandshake completed.
ASSERT_FALSE(ssl.WriteBeforeConfirm());
trans.reset();
session->CloseAllConnections();
}
TEST_F(HttpNetworkTransactionTest, ZeroRTTAsyncConfirmSyncWrite) {
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite(SYNCHRONOUS,
"POST / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 0\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a persistent
// connection.
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 1\r\n\r\n"),
MockRead(SYNCHRONOUS, "1"),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(SYNCHRONOUS, OK);
ssl.confirm = MockConfirm(ASYNC, OK);
session_deps_.enable_early_data = true;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
TestCompletionCallback callback;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(1, response->headers->GetContentLength());
// Check that the Write didn't get called before ConfirmHandshake completed.
ASSERT_FALSE(ssl.WriteBeforeConfirm());
trans.reset();
session->CloseAllConnections();
}
TEST_F(HttpNetworkTransactionTest, ZeroRTTAsyncConfirmAsyncWrite) {
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite(ASYNC,
"POST / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 0\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a persistent
// connection.
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 1\r\n\r\n"),
MockRead(SYNCHRONOUS, "1"),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(SYNCHRONOUS, OK);
ssl.confirm = MockConfirm(ASYNC, OK);
session_deps_.enable_early_data = true;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
TestCompletionCallback callback;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsOk());
const HttpResponseInfo* response = trans->GetResponseInfo();
ASSERT_TRUE(response);
ASSERT_TRUE(response->headers);
EXPECT_EQ(200, response->headers->response_code());
EXPECT_EQ(1, response->headers->GetContentLength());
// Check that the Write didn't get called before ConfirmHandshake completed.
ASSERT_FALSE(ssl.WriteBeforeConfirm());
trans.reset();
session->CloseAllConnections();
}
TEST_F(HttpNetworkTransactionTest, ZeroRTTConfirmErrorSync) {
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite("POST / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 0\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a persistent
// connection.
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 1\r\n\r\n"),
MockRead(SYNCHRONOUS, "1"),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(SYNCHRONOUS, OK);
ssl.confirm = MockConfirm(SYNCHRONOUS, ERR_SSL_PROTOCOL_ERROR);
session_deps_.enable_early_data = true;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
TestCompletionCallback callback;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_SSL_PROTOCOL_ERROR));
// Check that the Write didn't get called before ConfirmHandshake completed.
ASSERT_FALSE(ssl.WriteBeforeConfirm());
trans.reset();
session->CloseAllConnections();
}
TEST_F(HttpNetworkTransactionTest, ZeroRTTConfirmErrorAsync) {
HttpRequestInfo request;
request.method = "POST";
request.url = GURL("https://www.example.org/");
request.traffic_annotation =
net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS);
MockWrite data_writes[] = {
MockWrite("POST / HTTP/1.1\r\n"
"Host: www.example.org\r\n"
"Connection: keep-alive\r\n"
"Content-Length: 0\r\n\r\n"),
};
// The proxy responds to the connect with a 407, using a persistent
// connection.
MockRead data_reads[] = {
MockRead("HTTP/1.1 200 OK\r\n"),
MockRead("Content-Length: 1\r\n\r\n"),
MockRead(SYNCHRONOUS, "1"),
};
StaticSocketDataProvider data(data_reads, data_writes);
session_deps_.socket_factory->AddSocketDataProvider(&data);
SSLSocketDataProvider ssl(SYNCHRONOUS, OK);
ssl.confirm = MockConfirm(ASYNC, ERR_SSL_PROTOCOL_ERROR);
session_deps_.enable_early_data = true;
session_deps_.socket_factory->AddSSLSocketDataProvider(&ssl);
std::unique_ptr<HttpNetworkSession> session(CreateSession(&session_deps_));
TestCompletionCallback callback;
auto trans =
std::make_unique<HttpNetworkTransaction>(DEFAULT_PRIORITY, session.get());
int rv = trans->Start(&request, callback.callback(), NetLogWithSource());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
rv = callback.WaitForResult();
EXPECT_THAT(rv, IsError(ERR_SSL_PROTOCOL_ERROR));
// Check that the Write didn't get called before ConfirmHandshake completed.
ASSERT_FALSE(ssl.WriteBeforeConfirm());
trans.reset();
session->CloseAllConnections();
}
} // namespace net
| [
"279687673@qq.com"
] | 279687673@qq.com |
de2b205e1edbd394b15fee753ab3ae280d0ba9ec | b62a2498f227f9dee8c999bef091b08f2338ce78 | /src/ControlWithLabel.cpp | eaf775241184e60e0f59a06c27412e3c0533b56c | [
"MIT"
] | permissive | morphogencc/Cinder-UI | 864c6d8a6260cb5becdedb4fe7e7802fce94b7b4 | c69aa02fdf0ad5d60bfb270c35f10bfc590f6850 | refs/heads/master | 2020-03-24T19:11:56.954176 | 2020-03-07T20:06:55 | 2020-03-07T20:06:55 | 142,911,467 | 0 | 0 | null | 2018-07-30T18:11:18 | 2018-07-30T18:11:18 | null | UTF-8 | C++ | false | false | 422 | cpp | #include "ControlWithLabel.h"
using namespace reza::ui;
using namespace ci;
using namespace std;
ControlWithLabel::ControlWithLabel()
: Control()
{
}
ControlWithLabel::~ControlWithLabel()
{
}
void ControlWithLabel::changeState()
{
Control::changeState();
if( mLabelRef ) mLabelRef->setState( mState );
}
void ControlWithLabel::setLabel( const std::string &label )
{
if( mLabelRef ) mLabelRef->setLabel( label );
} | [
"syed.reza.ali@gmail.com"
] | syed.reza.ali@gmail.com |
2ef6c8d02d962ceb725f9cabf6f3d5bbe715a7a9 | 3adef134af0da3b55f11fa3f8dc80cfc4e8c8fc3 | /LRU_cache.cpp | ced7d73eeda2e9ea1d08cfbb017d0dbd8d223c67 | [] | no_license | starmap0312/leetcode | fb402525050ea0cee5e663165d306d9c4cbaafdf | 9d99ad4de20f36bc511c0c141b75b2515d04cc38 | refs/heads/master | 2021-01-04T14:22:04.566212 | 2020-11-10T03:05:08 | 2020-11-10T03:05:08 | 39,904,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,563 | cpp | /* - use doubly-linked list to keep the recently used elements
* ex. head tail
* key 4 --> 2 --> 1
* value 1 <-- 3 <-- 1
* - most recently used element is put at the head, whereas least recently used element is
* put at the tail
* when get or set an element, update the head and the tail if necessay
* - use a hash mapping from keys to pointers to quickly access the elements of the list
* when the size of the list/map exceeds the capacity, delete and update the tail
*/
#include <iostream>
#include <unordered_map>
using namespace std;
class Node {
public:
Node *next, *prev;
int key, value;
Node(int k, int v) : key(k), value(v), next(NULL), prev(NULL) { }
};
class LRUCache{
public:
LRUCache(int capacity) {
maxSize = capacity;
head = tail = NULL;
}
int get(int key) {
unordered_map<int, Node*>::iterator itr = mp.find(key);
if (itr == mp.end()) return -1;
else {
Node *found = itr -> second;
if (head != found) {
if (found == tail) tail = tail -> prev;
if (found -> prev != NULL) (found -> prev) -> next = found -> next;
if (found -> next != NULL) (found -> next) -> prev = found -> prev;
head -> prev = found;
found -> next = head, found -> prev = NULL;
head = found;
}
return found -> value;
}
}
void set(int key, int value) {
unordered_map<int, Node*>::iterator itr = mp.find(key);
if (itr == mp.end()) {
if (mp.size() == 0) {
head = tail = new Node(key, value);
} else {
Node *tmp = head;
head = new Node(key, value);
head -> next = tmp;
tmp -> prev = head;
}
mp[key] = head;
if (mp.size() > maxSize) {
Node *tmp = tail;
tail = tail -> prev;
tail -> next = NULL;
mp.erase(tmp -> key);
delete tmp;
}
} else {
(itr -> second) -> value = value;
get(key);
}
}
private:
Node *head, *tail;
unordered_map<int, Node*> mp;
int maxSize;
};
int main() {
LRUCache cache(2);
cache.set(2, 1);
cache.set(1, 1);
cache.set(2, 3);
cache.set(4, 1);
cout << cache.get(1) << endl;
cout << cache.get(2) << endl;
return 0;
}
| [
"starmap0312@gmail.com"
] | starmap0312@gmail.com |
6be1fd378687beaaf1659f5c2409a122a7faa4a5 | a756eed9030c5afa645436412d777a1774357c70 | /dsa/Graphs/Strongly _connected _components_with backedge.cpp | b5dd8293df1c5cf83c2a7da47bb8b109dfb6c04b | [] | no_license | jainsourav43/DSA | fc92faa7f8e95151c8f0af4c69228d4db7e1e5ce | deb46f70a1968b44bb28389d01b35cb571a8c293 | refs/heads/master | 2021-05-25T09:13:42.418930 | 2020-06-30T07:36:56 | 2020-06-30T07:36:56 | 126,943,860 | 0 | 1 | null | 2020-06-30T07:36:57 | 2018-03-27T07:07:51 | C++ | UTF-8 | C++ | false | false | 3,302 | cpp | #include<iostream>
using namespace std;
struct queue
{
int size;
int element[50];
int front;
int rear;
};
struct stack
{
int top;
int size;
int ele[5];
};
void enque(queue &q,int x)
{
if((q.rear+1)%q.size==q.front)
{
cout<<"Queue is overloaded\n";
}
else
{
if(q.front==-1)
q.front=0;
q.rear=(q.rear+1)%q.size;
q.element[q.rear]=x;
}
}
int deque(queue &q)
{
int t;
if(q.front==-1)
{
cout<<"Queue is Empty\n";
}
else
{
t=q.front;
if(q.front==q.rear)
{
q.front=-1;
q.rear=-1;
}
else
{
q.front=(q.front+1)%q.size;
}
return q.element[t];
}
}
int a[50][50]={0},n;
int in_degree(int n,int v)
{
int dg=0;
for(int i=1;i<=n;i++)
{
if(a[v][i]==1)
{
dg++;
}
}
return dg-1;
}
int out_degree(int n,int v)
{
int dg=0;
for(int i=0;i<n;i++){
if(a[v][i]==1)
{
dg++;
}
}
return dg-1;
}
void print(int a[][50],int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}
int ve[50];
int count[50];
int s;
int number[20];
int ans=1;
int parent[20];
int findmin(int a,int b,int c)
{
if(a<=b&&a<=c)
return a;
else if(b<=a&&b<=c)
return b;
else
return c;
}
int si=0,dft_tree[20];
void dfs(int v,int n)
{
int i;static int ans=1;
if(ve[v]==0)
{
ve[v]=1;
number[v]=ans++;
dft_tree[si++]=v;
cout<<v<<" ";
for(i=1;i<=n;i++)
{
if(a[v][i]>0&&ve[i]==0)
{
count[i]++;
parent[i]=v;
dfs(i,n);
}
}
}
}
int lowv[20]={0},low[20];
int bvi[20]={0};
void findlow(int v)
{
if(lowv[v]==0){
int i,j,min=1000,k,min2=1000,min3=1000;
lowv[v]=1;
for(i=1;i<=n;i++)
{
if(lowv[i]==1&&v==parent[i])
{
if(min>low[i])
{
min=low[i];
}
}
else if(lowv[i]==0&&v==parent[i])
{
findlow(i);
k=low[i];
if(min>k)
min=k;
}
}
min2=number[v];
int check=0;
for(i=1;i<=n;i++)
{
if(a[v][i]>0)
{
if(i!=parent[v]&&v!=parent[i])
{
if(min3>number[i])
{
min3=number[i];
}
}
}
}
low[v]=findmin(min,min2,min3);
}
}
int main()
{
int n1,i,ou,j;
queue q;
q.front=-1;
q.rear=-1;
q.size=50;
cout<<"Enter the number of vertices\n";
cin>>n;int check,max;
for(i=1;i<=n;i++)
{
ve[i]=0;
count[i] =0;
}
int in[n],u,v,i1;
cout<<"Enter the number of edges\n";
cin>>n1;int un[n1],vn[n1];
for(i=0;i<n1;i++)
{
cout<<"enter the u and v 'u->v' \n";
cin>>u>>v;
a[u][v]=1;
}
cout<<"enter the starting vertex\n";
cin>>s;
count[s]++;
parent[s]=-1;
cout<<"\nDFS is \n";
dfs(s,n);cout<<endl;
while(check==0)
{
for(i=1;i<=n;i++)
{
if(ve[i]==0)
{
dfs(i,n);
cout<<endl;
}
}
for(j=1;j<=n;j++)
{
if(ve[j]==1)
{
check=1;
}
else if(ve[j]==0)
{
check=0;
break;
}
}
}
cout<<"Numbered array\n";
for(i=1;i<=n;i++)
{
cout<<number[i]<<" ";
}
for(i=n;i>0;i--)
{
if(lowv[i]==0)
findlow(i);
}
cout<<"Low of vertices are\n";
for(i=1;i<=n;i++)
{
cout<<low[i]<<" ";
}
for(i=1;i<=n;i++)
{
if(low[i]<number[i])
{
cout<<i<<" ";
}
}
return 0;
}
| [
"jainsourav43@gmail.com"
] | jainsourav43@gmail.com |
26f9bc83b6f87b7132a67994d1d42aad8c5076fc | fae551eb54ab3a907ba13cf38aba1db288708d92 | /chrome/browser/ash/web_applications/help_app/help_app_discover_tab_notification_unittest.cc | 0930803f8dd02d010f944dc5b02a052fb3724bc0 | [
"BSD-3-Clause"
] | permissive | xtblock/chromium | d4506722fc6e4c9bc04b54921a4382165d875f9a | 5fe0705b86e692c65684cdb067d9b452cc5f063f | refs/heads/main | 2023-04-26T18:34:42.207215 | 2021-05-27T04:45:24 | 2021-05-27T04:45:24 | 371,258,442 | 2 | 1 | BSD-3-Clause | 2021-05-27T05:36:28 | 2021-05-27T05:36:28 | null | UTF-8 | C++ | false | false | 5,122 | cc | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ash/web_applications/help_app/help_app_discover_tab_notification.h"
#include "base/test/metrics/user_action_tester.h"
#include "base/test/mock_callback.h"
#include "chrome/browser/notifications/notification_display_service_tester.h"
#include "chrome/browser/notifications/notification_handler.h"
#include "chrome/browser/notifications/system_notification_helper.h"
#include "chrome/browser/ui/web_applications/system_web_app_ui_utils.h"
#include "chrome/browser/web_applications/system_web_apps/system_web_app_types.h"
#include "chrome/test/base/browser_with_test_window_test.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
namespace chromeos {
class HelpAppDiscoverTabNotificationTest : public BrowserWithTestWindowTest {
public:
HelpAppDiscoverTabNotificationTest() {}
~HelpAppDiscoverTabNotificationTest() override = default;
HelpAppDiscoverTabNotificationTest(
const HelpAppDiscoverTabNotificationTest&) = delete;
HelpAppDiscoverTabNotificationTest& operator=(
const HelpAppDiscoverTabNotificationTest&) = delete;
TestingProfile* CreateProfile() override {
return profile_manager()->CreateTestingProfile("user@gmail.com");
}
void SetUp() override {
BrowserWithTestWindowTest::SetUp();
TestingBrowserProcess::GetGlobal()->SetSystemNotificationHelper(
std::make_unique<SystemNotificationHelper>());
discover_tab_notification_ =
std::make_unique<HelpAppDiscoverTabNotification>(profile());
notification_tester_ =
std::make_unique<NotificationDisplayServiceTester>(nullptr);
}
void TearDown() override {
discover_tab_notification_.reset();
notification_tester_.reset();
BrowserWithTestWindowTest::TearDown();
}
protected:
bool HasDiscoverTabNotification() {
return notification_tester_
->GetNotification(kShowHelpAppDiscoverTabNotificationId)
.has_value();
}
message_center::Notification GetDiscoverTabNotification() {
return notification_tester_
->GetNotification(kShowHelpAppDiscoverTabNotificationId)
.value();
}
std::unique_ptr<HelpAppDiscoverTabNotification> discover_tab_notification_;
std::unique_ptr<NotificationDisplayServiceTester> notification_tester_;
};
TEST_F(HelpAppDiscoverTabNotificationTest, ShowsNotificationCorrectly) {
discover_tab_notification_->Show();
EXPECT_EQ(true, HasDiscoverTabNotification());
EXPECT_EQ("Design and build your own games",
base::UTF16ToASCII(GetDiscoverTabNotification().title()));
EXPECT_EQ("Learn from a game creator, get game design apps, and more",
base::UTF16ToASCII(GetDiscoverTabNotification().message()));
}
TEST_F(HelpAppDiscoverTabNotificationTest, LogsMetricWhenNotificationShown) {
base::UserActionTester user_action_tester;
EXPECT_EQ(0, user_action_tester.GetActionCount(
"Discover.DiscoverTabNotification.Shown"));
discover_tab_notification_->Show();
EXPECT_EQ(1, user_action_tester.GetActionCount(
"Discover.DiscoverTabNotification.Shown"));
}
TEST_F(HelpAppDiscoverTabNotificationTest, ClickingNotificationDismissesIt) {
discover_tab_notification_->Show();
notification_tester_->SimulateClick(NotificationHandler::Type::TRANSIENT,
kShowHelpAppDiscoverTabNotificationId,
/*action_index=*/0,
/*reply=*/absl::nullopt);
EXPECT_EQ(false, HasDiscoverTabNotification());
}
TEST_F(HelpAppDiscoverTabNotificationTest,
ClickingNotificationCallsOnClickCallback) {
base::MockCallback<base::RepeatingClosure> mock_callback;
EXPECT_CALL(mock_callback, Run());
discover_tab_notification_->SetOnClickCallbackForTesting(mock_callback.Get());
discover_tab_notification_->Show();
notification_tester_->SimulateClick(NotificationHandler::Type::TRANSIENT,
kShowHelpAppDiscoverTabNotificationId,
/*action_index=*/0,
/*reply=*/absl::nullopt);
EXPECT_EQ(false, HasDiscoverTabNotification());
}
TEST_F(HelpAppDiscoverTabNotificationTest, LogsMetricWhenNotificationClicked) {
base::UserActionTester user_action_tester;
discover_tab_notification_->Show();
EXPECT_EQ(0, user_action_tester.GetActionCount(
"Discover.DiscoverTabNotification.Clicked"));
notification_tester_->SimulateClick(NotificationHandler::Type::TRANSIENT,
kShowHelpAppDiscoverTabNotificationId,
/*action_index=*/0,
/*reply=*/absl::nullopt);
EXPECT_EQ(1, user_action_tester.GetActionCount(
"Discover.DiscoverTabNotification.Clicked"));
}
} // namespace chromeos
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
f9d623267c033a6e82fca7fb5445b45ae28d8443 | 2ac1753652a65cb0beb4d1f83ae860060741d4f0 | /MartaVegaBayo_MasterThesis/PubmedParser/AbstractParser.h | 4ba7b705e2e3aedba3512367c9b206407c38caa5 | [] | no_license | marta123456/ReferenceRecommendationForScientificArticles | b732acaf6b018876a60fda9c3e7f5a7edb30c3c5 | 762fa608427efb983f73daa23f0d61187dc8ae8f | refs/heads/master | 2021-01-10T07:18:59.057105 | 2016-01-24T09:41:56 | 2016-01-24T09:41:56 | 50,256,680 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 688 | h | //Declaration of the class AbstractParser
#if !defined (_ABSTRACTPARSER_H_)
#define _ABSTRACTPARSER_H_
#include "../DataModel/CArticleParsed.h"
#include "../Pugixml/pugixml.hpp"
#include "ParserBase.h"
/**
AbstractParser class.
This class has methods and attributes to parse from the DOM of an XML article with the JATS schema the abstract of the article and set with it the corresponding attribute of the CArticleParsed object inherited form ParserBase.
*/
class AbstractParser: public virtual ParserBase
{
private:
pugi::xml_node aArticleMetaNode; //DOM node from where the abstract will be looked for
public:
void loadXMLnodes(pugi::xml_node &rootNode);
void parse();
};
#endif
| [
"martavegabayo@gmail.com"
] | martavegabayo@gmail.com |
1b430879275db5bdcff91a3608df64446a65a5d8 | a3f825ea90fa6038dd50f05409fc51f960eb3856 | /OTA.ino | e69e0ec8e19262638dc8553b445dc4cd84d5891c | [] | no_license | PanegyricLyric/NODEMCU-OTA-BLYNK-LED | d6f46ba7f0a16b9eef2428f704a275b745e80d3e | 5a827361e21189b94a489f6e3e058c2acfffc764 | refs/heads/master | 2020-03-23T14:52:49.330593 | 2018-11-17T21:38:34 | 2018-11-17T21:38:34 | 141,705,237 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,042 | ino | //---------------------------FOR-WIFI-UPDATE----------------------SETUP
void OTA_Conf(){
Serial.println("Booting");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.waitForConnectResult() != WL_CONNECTED)
{
Serial.println("Connection Failed! Rebooting...");
delay(5000);
ESP.restart();
}
// Port defaults to 8266
// ArduinoOTA.setPort(8266);
ArduinoOTA.setHostname("esp8266");
// No authentication by default
// ArduinoOTA.setPassword("admin");
// Password can be set with it's md5 value as well
// MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
// ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");
ArduinoOTA.onStart([]()
{
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
});
ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
Serial.println("Ready");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
| [
"39015426+PanegyricLyric@users.noreply.github.com"
] | 39015426+PanegyricLyric@users.noreply.github.com |
4ef4be8ea52b65e8b9428002122ad3ce2d70a913 | a94d0b0346493372ef475781c417b62b04cf4ed7 | /compose.cpp | 7937ecd68b040988b32d98571e7bd86bcaefd71a | [] | no_license | VibhuGautam/Cpp | ad8878b0a13d4275bc4bdb85de5cd92695fbab08 | 5a9ed7a3a1ed420ec505dcde04ab50597d01e26d | refs/heads/master | 2023-04-22T22:34:23.790941 | 2021-04-25T05:39:59 | 2021-04-25T05:39:59 | 361,340,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,041 | cpp | /*------------------------------------
Author : Vibhu Gautam
Date = 24/04/2021
Time = 10:57:50
------------------------------------*/
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 998244353 , mod = 1e9 + 7;
#define rep(i,a,b) for(ll i = a; i < b; ++i)
#define repr(i,a,b) for(ll i = a; i >= b; --i)
#define pb push_back
#define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
// compose(g, f) -- returns a function h such that h(x) == g(f(x)).
template <typename Function> auto COMPOSE(Function f, Function g)
{
return [f, g](auto const &input) { return f(g(input)); };
}
ll a(ll x)
{
return 2 * x;
}
ll b(ll x)
{
return 3 * x;
}
void solve()
{
auto h = COMPOSE(a, b);
cout << h(2);
}
int main()
{
fast_cin();
ll t = 1;
// cin >> t;
for(ll it=1;it<=t;it++) {
solve();
}
return 0;
} | [
"vibhuparmar13@gmail.com"
] | vibhuparmar13@gmail.com |
56f95a32d82e982bab0f45d3abd4ee867826d463 | b27cbaad60e5489353d3c78c8e5784d6f7bfa1d6 | /unityplugin/UnityEmulator/src/DiligentGraphicsAdapterD3D12.cpp | 18e2ae0197f0700c995ce3a29e1c96ce91ebe8eb | [
"Apache-2.0"
] | permissive | southdy/DiligentEngine | 55ad45b3b1754e5efe26e76b372f13d84214392c | b8d12b47de3213beb873630ca4a9c0110d875334 | refs/heads/master | 2020-05-07T18:25:22.789723 | 2019-04-07T20:24:13 | 2019-04-07T20:24:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,488 | cpp |
#include <array>
#define NOMINMAX
#include <D3D12.h>
#include <dxgi1_4.h>
#include <atlbase.h>
#include "UnityGraphicsD3D12Impl.h"
#include "DiligentGraphicsAdapterD3D12.h"
#include "UnityGraphicsD3D12Emulator.h"
#include "SwapChainD3D12.h"
#include "TextureD3D12.h"
#include "RenderDeviceD3D12.h"
#include "DeviceContextD3D12.h"
#include "CommandQueueD3D12.h"
#include "EngineFactoryD3D12.h"
#include "SwapChainBase.h"
#include "DefaultRawMemoryAllocator.h"
#include "DXGITypeConversions.h"
using namespace Diligent;
namespace
{
class ProxyCommandQueueD3D12 : public ObjectBase<ICommandQueueD3D12>
{
public:
using TBase = ObjectBase<ICommandQueueD3D12>;
ProxyCommandQueueD3D12(IReferenceCounters *pRefCounters, UnityGraphicsD3D12Impl& GraphicsD3D12Impl) :
TBase(pRefCounters),
m_GraphicsD3D12Impl(GraphicsD3D12Impl)
{
}
~ProxyCommandQueueD3D12()
{
}
IMPLEMENT_QUERY_INTERFACE_IN_PLACE( IID_CommandQueueD3D12, TBase )
// Returns the fence value that will be signaled next time
virtual Uint64 GetNextFenceValue()override final
{
return m_GraphicsD3D12Impl.GetNextFenceValue();
}
// Executes a given command list
virtual Uint64 Submit(ID3D12GraphicsCommandList* commandList)override final
{
return m_GraphicsD3D12Impl.ExecuteCommandList(commandList);
}
// Returns D3D12 command queue. May return null if queue is anavailable
virtual ID3D12CommandQueue* GetD3D12CommandQueue()
{
return nullptr;
}
/// Returns value of the last completed fence
virtual Uint64 GetCompletedFenceValue()override final
{
return m_GraphicsD3D12Impl.GetCompletedFenceValue();
}
/// Blocks execution until all pending GPU commands are complete
virtual Uint64 WaitForIdle()override final
{
return m_GraphicsD3D12Impl.IdleGPU();
}
virtual void SignalFence(ID3D12Fence* pFence, Uint64 Value)override final
{
m_GraphicsD3D12Impl.GetCommandQueue()->Signal(pFence, Value);
}
private:
UnityGraphicsD3D12Impl& m_GraphicsD3D12Impl;
};
class ProxySwapChainD3D12 : public SwapChainBase<ISwapChainD3D12>
{
public:
using TBase = SwapChainBase<ISwapChainD3D12>;
ProxySwapChainD3D12( IReferenceCounters *pRefCounters,
IRenderDevice *pDevice,
IDeviceContext *pDeviceContext,
const SwapChainDesc& SCDesc ) :
TBase(pRefCounters, pDevice, pDeviceContext,SCDesc)
{
}
IMPLEMENT_QUERY_INTERFACE_IN_PLACE(IID_SwapChainD3D12, TBase)
virtual IDXGISwapChain *GetDXGISwapChain()override final
{
UNEXPECTED("DXGI swap chain cannot be requested through the proxy swap chain");
return nullptr;
}
virtual ITextureViewD3D12* GetCurrentBackBufferRTV()
{
return m_RTVs[m_CurrentBackBufferIndex];
}
virtual ITextureViewD3D12* GetDepthBufferDSV()
{
return m_DSV;
}
virtual void Present(Uint32 SyncInterval)override final
{
UNEXPECTED("Present is not expected to be called directly");
}
virtual void SetFullscreenMode(const DisplayModeAttribs &DisplayMode)override final
{
UNEXPECTED("Fullscreen mode cannot be set through the proxy swap chain");
}
virtual void SetWindowedMode()override final
{
UNEXPECTED("Windowed mode cannot be set through the proxy swap chain");
}
virtual void Resize(Uint32 NewWidth, Uint32 NewHeight)override final
{
TBase::Resize(NewWidth, NewHeight, 0);
}
void ReleaseBuffers()
{
m_BackBuffers.clear();
m_RTVs.clear();
m_DepthBuffer.Release();
m_DSV.Release();
}
void SetBackBufferIndex(Uint32 BackBufferIndex) { m_CurrentBackBufferIndex = BackBufferIndex; }
void CreateBuffers(IDXGISwapChain3 *pDXGISwapChain, ID3D12Resource *pd3d12DepthBuffer)
{
DXGI_SWAP_CHAIN_DESC1 SwapChainDesc;
pDXGISwapChain->GetDesc1(&SwapChainDesc);
m_SwapChainDesc.BufferCount = SwapChainDesc.BufferCount;
m_SwapChainDesc.SamplesCount = SwapChainDesc.SampleDesc.Count;
m_SwapChainDesc.Width = SwapChainDesc.Width;
m_SwapChainDesc.Height = SwapChainDesc.Height;
m_SwapChainDesc.ColorBufferFormat = DXGI_FormatToTexFormat(SwapChainDesc.Format);
const auto DepthBufferDesc = pd3d12DepthBuffer->GetDesc();
m_SwapChainDesc.DepthBufferFormat = DXGI_FormatToTexFormat(DepthBufferDesc.Format);
RefCntAutoPtr<IRenderDeviceD3D12> pRenderDeviceD3D12(m_pRenderDevice, IID_RenderDeviceD3D12);
m_BackBuffers.reserve(m_SwapChainDesc.BufferCount);
m_RTVs.reserve(m_SwapChainDesc.BufferCount);
for(Uint32 backbuff = 0; backbuff < m_SwapChainDesc.BufferCount; ++backbuff)
{
CComPtr<ID3D12Resource> pd3d12BackBuffer;
auto hr = pDXGISwapChain->GetBuffer(backbuff, __uuidof(pd3d12BackBuffer), reinterpret_cast<void**>( static_cast<ID3D12Resource**>(&pd3d12BackBuffer) ));
if(FAILED(hr))
LOG_ERROR_AND_THROW("Failed to get back buffer ", backbuff," from the swap chain");
RefCntAutoPtr<ITexture> pBackBuffer;
pRenderDeviceD3D12->CreateTextureFromD3DResource(pd3d12BackBuffer, RESOURCE_STATE_UNDEFINED, &pBackBuffer);
m_BackBuffers.emplace_back( RefCntAutoPtr<ITextureD3D12>(pBackBuffer, IID_TextureD3D12) );
TextureViewDesc TexViewDesc;
TexViewDesc.ViewType = TEXTURE_VIEW_RENDER_TARGET;
TexViewDesc.Format = TEX_FORMAT_RGBA8_UNORM_SRGB;
RefCntAutoPtr<ITextureView> pRTV;
pBackBuffer->CreateView(TexViewDesc, &pRTV);
m_RTVs.emplace_back(RefCntAutoPtr<ITextureViewD3D12>(pRTV, IID_TextureViewD3D12));
}
RefCntAutoPtr<ITexture> pDepthBuffer;
pRenderDeviceD3D12->CreateTextureFromD3DResource(pd3d12DepthBuffer, RESOURCE_STATE_UNDEFINED, &pDepthBuffer);
m_DepthBuffer = RefCntAutoPtr<ITextureD3D12>(pDepthBuffer, IID_TextureD3D12);
auto *pDSV = m_DepthBuffer->GetDefaultView(TEXTURE_VIEW_DEPTH_STENCIL);
m_DSV = RefCntAutoPtr<ITextureViewD3D12>(pDSV, IID_TextureViewD3D12);
}
ITextureD3D12* GetCurrentBackBuffer() { return m_BackBuffers[m_CurrentBackBufferIndex]; }
ITextureD3D12* GetDepthBuffer() { return m_DepthBuffer; }
private:
std::vector<RefCntAutoPtr<ITextureD3D12>> m_BackBuffers;
std::vector<RefCntAutoPtr<ITextureViewD3D12>> m_RTVs;
RefCntAutoPtr<ITextureD3D12> m_DepthBuffer;
RefCntAutoPtr<ITextureViewD3D12> m_DSV;
Uint32 m_CurrentBackBufferIndex = 0;
};
}
DiligentGraphicsAdapterD3D12::DiligentGraphicsAdapterD3D12(UnityGraphicsD3D12Emulator& UnityGraphicsD3D12)noexcept :
m_UnityGraphicsD3D12(UnityGraphicsD3D12)
{
auto *GraphicsImpl = UnityGraphicsD3D12.GetGraphicsImpl();
auto *d3d12Device = GraphicsImpl->GetD3D12Device();
auto &DefaultAllocator = DefaultRawMemoryAllocator::GetAllocator();
auto CmdQueue = NEW_RC_OBJ(DefaultAllocator, "UnityCommandQueueImpl instance", ProxyCommandQueueD3D12)(*GraphicsImpl);
auto *pFactoryD3D12 = GetEngineFactoryD3D12();
EngineD3D12CreateInfo Attribs;
std::array<ICommandQueueD3D12*, 1> CmdQueues = {CmdQueue};
pFactoryD3D12->AttachToD3D12Device(d3d12Device, CmdQueues.size(), CmdQueues.data(), Attribs, &m_pDevice, &m_pDeviceCtx);
}
void DiligentGraphicsAdapterD3D12::InitProxySwapChain()
{
auto *GraphicsImpl = m_UnityGraphicsD3D12.GetGraphicsImpl();
auto &DefaultAllocator = DefaultRawMemoryAllocator::GetAllocator();
SwapChainDesc SCDesc;
auto ProxySwapChain = NEW_RC_OBJ(DefaultAllocator, "UnityCommandQueueImpl instance", ProxySwapChainD3D12)(m_pDevice, m_pDeviceCtx, SCDesc);
ProxySwapChain->CreateBuffers(GraphicsImpl->GetDXGISwapChain(), GraphicsImpl->GetDepthBuffer());
m_pProxySwapChain = ProxySwapChain;
m_pDeviceCtx->SetSwapChain(ProxySwapChain);
}
void DiligentGraphicsAdapterD3D12::PreSwapChainResize()
{
auto *pProxySwapChainD3D12 = m_pProxySwapChain.RawPtr<ProxySwapChainD3D12>();
auto *pDeviceD3D12 = m_pDevice.RawPtr<IRenderDeviceD3D12>();
pProxySwapChainD3D12->ReleaseBuffers();
auto *GraphicsImpl = m_UnityGraphicsD3D12.GetGraphicsImpl();
pDeviceD3D12->ReleaseStaleResources();
// We must idle GPU
GraphicsImpl->IdleGPU();
// And call FinishFrame() to release references to swap chain resources
m_pDeviceCtx->FinishFrame();
pDeviceD3D12->ReleaseStaleResources();
}
void DiligentGraphicsAdapterD3D12::PostSwapChainResize()
{
auto *GraphicsImpl = m_UnityGraphicsD3D12.GetGraphicsImpl();
auto *pProxySwapChainD3D12 = m_pProxySwapChain.RawPtr<ProxySwapChainD3D12>();
pProxySwapChainD3D12->CreateBuffers(GraphicsImpl->GetDXGISwapChain(), GraphicsImpl->GetDepthBuffer());
}
void DiligentGraphicsAdapterD3D12::BeginFrame()
{
auto *GraphicsImpl = m_UnityGraphicsD3D12.GetGraphicsImpl();
auto *pProxySwapChainD3D12 = m_pProxySwapChain.RawPtr<ProxySwapChainD3D12>();
pProxySwapChainD3D12->SetBackBufferIndex(GraphicsImpl->GetCurrentBackBufferIndex());
// Unity graphics emulator transitions render target to D3D12_RESOURCE_STATE_RENDER_TARGET,
// and depth buffer to D3D12_RESOURCE_STATE_DEPTH_WRITE state
pProxySwapChainD3D12->GetCurrentBackBuffer()->SetD3D12ResourceState(D3D12_RESOURCE_STATE_RENDER_TARGET);
pProxySwapChainD3D12->GetDepthBuffer()->SetD3D12ResourceState(D3D12_RESOURCE_STATE_DEPTH_WRITE);
}
void DiligentGraphicsAdapterD3D12::EndFrame()
{
// Unity graphics emulator expects render target to be D3D12_RESOURCE_STATE_RENDER_TARGET,
// and depth buffer to be in D3D12_RESOURCE_STATE_DEPTH_WRITE state
auto *pCtxD3D12 = m_pDeviceCtx.RawPtr<IDeviceContextD3D12>();
auto *pProxySwapChainD3D12 = m_pProxySwapChain.RawPtr<ProxySwapChainD3D12>();
auto *pCurrentBackBuffer = pProxySwapChainD3D12->GetCurrentBackBuffer();
auto *pDepthBuffer = pProxySwapChainD3D12->GetDepthBuffer();
pCtxD3D12->TransitionTextureState(pCurrentBackBuffer, D3D12_RESOURCE_STATE_RENDER_TARGET);
pCtxD3D12->TransitionTextureState(pDepthBuffer, D3D12_RESOURCE_STATE_DEPTH_WRITE);
m_pDeviceCtx->Flush();
m_pDeviceCtx->FinishFrame();
m_pDeviceCtx->InvalidateState();
m_pDevice.RawPtr<IRenderDeviceD3D12>()->ReleaseStaleResources();
}
bool DiligentGraphicsAdapterD3D12::UsesReverseZ()
{
return m_UnityGraphicsD3D12.UsesReverseZ();
}
| [
"egor.yusov@gmail.com"
] | egor.yusov@gmail.com |
2faa825f7a32691fa9c7082aa4574d13d8aa6175 | 3051bd4bc0b7f3dace598880caf3364690688bc9 | /plugins/MacVST/Ditherbox/source/DitherboxProc.cpp | 4115687873088b35974a8888861ed9978ed0a7f2 | [
"MIT"
] | permissive | Atavic/airwindows | aa6802409eb9c7254e405874a267af700cb6ba0d | ac8d974fb5bfa349af37412aa5e1fe2aeea1a8f6 | refs/heads/master | 2020-03-28T08:38:49.668758 | 2018-09-09T01:07:53 | 2018-09-09T01:07:53 | 147,978,977 | 1 | 0 | MIT | 2018-09-09T00:02:49 | 2018-09-09T00:02:49 | null | UTF-8 | C++ | false | false | 81,998 | cpp | /* ========================================
* Ditherbox - Ditherbox.h
* Copyright (c) 2016 airwindows, All rights reserved
* ======================================== */
#ifndef __Ditherbox_H
#include "Ditherbox.h"
#endif
void Ditherbox::processReplacing(float **inputs, float **outputs, VstInt32 sampleFrames)
{
float* in1 = inputs[0];
float* in2 = inputs[1];
float* out1 = outputs[0];
float* out2 = outputs[1];
int dtype = (int)(A * 24.999)+1; // +1 for Reaper bug workaround
long double overallscale = 1.0;
overallscale /= 44100.0;
overallscale *= getSampleRate();
long double iirAmount = 2250/44100.0;
long double gaintarget = 1.42;
long double gain;
iirAmount /= overallscale;
long double altAmount = 1.0 - iirAmount;
long double outputSampleL;
long double outputSampleR;
long double silhouette;
long double smoother;
long double bridgerectifier;
long double benfordize;
int hotbinA;
int hotbinB;
long double totalA;
long double totalB;
long double contingentRnd;
long double absSample;
long double contingent;
long double randyConstant = 1.61803398874989484820458683436563811772030917980576;
long double omegaConstant = 0.56714329040978387299996866221035554975381578718651;
long double expConstant = 0.06598803584531253707679018759684642493857704825279;
long double trim = 2.302585092994045684017991; //natural logarithm of 10
bool highRes = false;
bool dithering = true;
if (dtype > 11){highRes = true; dtype -= 11;}
if (dtype > 11){dithering = false; highRes = false;}
//follow up by switching high res back off for the monitoring
while (--sampleFrames >= 0)
{
long double inputSampleL = *in1;
long double inputSampleR = *in2;
if (inputSampleL<1.2e-38 && -inputSampleL<1.2e-38) {
static int noisesource = 0;
//this declares a variable before anything else is compiled. It won't keep assigning
//it to 0 for every sample, it's as if the declaration doesn't exist in this context,
//but it lets me add this denormalization fix in a single place rather than updating
//it in three different locations. The variable isn't thread-safe but this is only
//a random seed and we can share it with whatever.
noisesource = noisesource % 1700021; noisesource++;
int residue = noisesource * noisesource;
residue = residue % 170003; residue *= residue;
residue = residue % 17011; residue *= residue;
residue = residue % 1709; residue *= residue;
residue = residue % 173; residue *= residue;
residue = residue % 17;
double applyresidue = residue;
applyresidue *= 0.00000001;
applyresidue *= 0.00000001;
inputSampleL = applyresidue;
}
if (inputSampleR<1.2e-38 && -inputSampleR<1.2e-38) {
static int noisesource = 0;
noisesource = noisesource % 1700021; noisesource++;
int residue = noisesource * noisesource;
residue = residue % 170003; residue *= residue;
residue = residue % 17011; residue *= residue;
residue = residue % 1709; residue *= residue;
residue = residue % 173; residue *= residue;
residue = residue % 17;
double applyresidue = residue;
applyresidue *= 0.00000001;
applyresidue *= 0.00000001;
inputSampleR = applyresidue;
//this denormalization routine produces a white noise at -300 dB which the noise
//shaping will interact with to produce a bipolar output, but the noise is actually
//all positive. That should stop any variables from going denormal, and the routine
//only kicks in if digital black is input. As a final touch, if you save to 24-bit
//the silence will return to being digital black again.
}
float drySampleL = inputSampleL;
float drySampleR = inputSampleR;
if (dtype == 8) {inputSampleL -= noiseShapingL; inputSampleR -= noiseShapingR;}
if (dithering) {inputSampleL *= 32768.0; inputSampleR *= 32768.0;}
//denormalizing as way of controlling insane detail boosting
if (highRes) {inputSampleL *= 256.0; inputSampleR *= 256.0;} //256 for 16/24 version
switch (dtype)
{
case 1:
inputSampleL = floor(inputSampleL);
inputSampleR = floor(inputSampleR);
//truncate
break;
case 2:
inputSampleL += (rand()/(double)RAND_MAX);
inputSampleL -= 0.5;
inputSampleL = floor(inputSampleL);
inputSampleR += (rand()/(double)RAND_MAX);
inputSampleR -= 0.5;
inputSampleR = floor(inputSampleR);
//flat dither
break;
case 3:
inputSampleL += (rand()/(double)RAND_MAX);
inputSampleL += (rand()/(double)RAND_MAX);
inputSampleL -= 1.0;
inputSampleL = floor(inputSampleL);
inputSampleR += (rand()/(double)RAND_MAX);
inputSampleR += (rand()/(double)RAND_MAX);
inputSampleR -= 1.0;
inputSampleR = floor(inputSampleR);
//TPDF dither
break;
case 4:
currentDitherL = (rand()/(double)RAND_MAX);
inputSampleL += currentDitherL;
inputSampleL -= lastSampleL;
inputSampleL = floor(inputSampleL);
lastSampleL = currentDitherL;
currentDitherR = (rand()/(double)RAND_MAX);
inputSampleR += currentDitherR;
inputSampleR -= lastSampleR;
inputSampleR = floor(inputSampleR);
lastSampleR = currentDitherR;
//Paul dither
break;
case 5:
nsL[9] = nsL[8]; nsL[8] = nsL[7]; nsL[7] = nsL[6]; nsL[6] = nsL[5];
nsL[5] = nsL[4]; nsL[4] = nsL[3]; nsL[3] = nsL[2]; nsL[2] = nsL[1];
nsL[1] = nsL[0]; nsL[0] = (rand()/(double)RAND_MAX);
currentDitherL = (nsL[0] * 0.061);
currentDitherL -= (nsL[1] * 0.11);
currentDitherL += (nsL[8] * 0.126);
currentDitherL -= (nsL[7] * 0.23);
currentDitherL += (nsL[2] * 0.25);
currentDitherL -= (nsL[3] * 0.43);
currentDitherL += (nsL[6] * 0.5);
currentDitherL -= nsL[5];
currentDitherL += nsL[4];
//this sounds different from doing it in order of sample position
//cumulative tiny errors seem to build up even at this buss depth
//considerably more pronounced at 32 bit float.
//Therefore we add the most significant components LAST.
//trying to keep values on like exponents of the floating point value.
inputSampleL += currentDitherL;
inputSampleL = floor(inputSampleL);
//done with L
nsR[9] = nsR[8]; nsR[8] = nsR[7]; nsR[7] = nsR[6]; nsR[6] = nsR[5];
nsR[5] = nsR[4]; nsR[4] = nsR[3]; nsR[3] = nsR[2]; nsR[2] = nsR[1];
nsR[1] = nsR[0]; nsR[0] = (rand()/(double)RAND_MAX);
currentDitherR = (nsR[0] * 0.061);
currentDitherR -= (nsR[1] * 0.11);
currentDitherR += (nsR[8] * 0.126);
currentDitherR -= (nsR[7] * 0.23);
currentDitherR += (nsR[2] * 0.25);
currentDitherR -= (nsR[3] * 0.43);
currentDitherR += (nsR[6] * 0.5);
currentDitherR -= nsR[5];
currentDitherR += nsR[4];
//this sounds different from doing it in order of sample position
//cumulative tiny errors seem to build up even at this buss depth
//considerably more pronounced at 32 bit float.
//Therefore we add the most significant components LAST.
//trying to keep values on like exponents of the floating point value.
inputSampleR += currentDitherR;
inputSampleR = floor(inputSampleR);
//done with R
//DoublePaul dither
break;
case 6:
currentDitherL = (rand()/(double)RAND_MAX);
currentDitherR = (rand()/(double)RAND_MAX);
inputSampleL += currentDitherL;
inputSampleR += currentDitherR;
inputSampleL -= nsL[4];
inputSampleR -= nsR[4];
inputSampleL = floor(inputSampleL);
inputSampleR = floor(inputSampleR);
nsL[4] = nsL[3];
nsL[3] = nsL[2];
nsL[2] = nsL[1];
nsL[1] = currentDitherL;
nsR[4] = nsR[3];
nsR[3] = nsR[2];
nsR[2] = nsR[1];
nsR[1] = currentDitherR;
//Tape dither
break;
case 7:
Position += 1;
//Note- uses integer overflow as a 'mod' operator
hotbinA = Position * Position;
hotbinA = hotbinA % 170003; //% is C++ mod operator
hotbinA *= hotbinA;
hotbinA = hotbinA % 17011; //% is C++ mod operator
hotbinA *= hotbinA;
hotbinA = hotbinA % 1709; //% is C++ mod operator
hotbinA *= hotbinA;
hotbinA = hotbinA % 173; //% is C++ mod operator
hotbinA *= hotbinA;
hotbinA = hotbinA % 17;
hotbinA *= 0.0635;
if (flip) hotbinA = -hotbinA;
inputSampleL += hotbinA;
inputSampleR += hotbinA;
inputSampleL = floor(inputSampleL);
inputSampleR = floor(inputSampleR);
//Quadratic dither
break;
case 8:
absSample = ((rand()/(double)RAND_MAX) - 0.5);
nsL[0] += absSample; nsL[0] /= 2; absSample -= nsL[0];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[1] += absSample; nsL[1] /= 2; absSample -= nsL[1];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[2] += absSample; nsL[2] /= 2; absSample -= nsL[2];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[3] += absSample; nsL[3] /= 2; absSample -= nsL[3];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[4] += absSample; nsL[4] /= 2; absSample -= nsL[4];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[5] += absSample; nsL[5] /= 2; absSample -= nsL[5];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[6] += absSample; nsL[6] /= 2; absSample -= nsL[6];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[7] += absSample; nsL[7] /= 2; absSample -= nsL[7];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[8] += absSample; nsL[8] /= 2; absSample -= nsL[8];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[9] += absSample; nsL[9] /= 2; absSample -= nsL[9];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[10] += absSample; nsL[10] /= 2; absSample -= nsL[10];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[11] += absSample; nsL[11] /= 2; absSample -= nsL[11];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[12] += absSample; nsL[12] /= 2; absSample -= nsL[12];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[13] += absSample; nsL[13] /= 2; absSample -= nsL[13];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[14] += absSample; nsL[14] /= 2; absSample -= nsL[14];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[15] += absSample; nsL[15] /= 2; absSample -= nsL[15];
//install noise and then shape it
absSample += inputSampleL;
if (NSOddL > 0) NSOddL -= 0.97;
if (NSOddL < 0) NSOddL += 0.97;
NSOddL -= (NSOddL * NSOddL * NSOddL * 0.475);
NSOddL += prevL;
absSample += (NSOddL*0.475);
prevL = floor(absSample) - inputSampleL;
inputSampleL = floor(absSample);
//TenNines dither L
absSample = ((rand()/(double)RAND_MAX) - 0.5);
nsR[0] += absSample; nsR[0] /= 2; absSample -= nsR[0];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[1] += absSample; nsR[1] /= 2; absSample -= nsR[1];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[2] += absSample; nsR[2] /= 2; absSample -= nsR[2];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[3] += absSample; nsR[3] /= 2; absSample -= nsR[3];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[4] += absSample; nsR[4] /= 2; absSample -= nsR[4];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[5] += absSample; nsR[5] /= 2; absSample -= nsR[5];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[6] += absSample; nsR[6] /= 2; absSample -= nsR[6];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[7] += absSample; nsR[7] /= 2; absSample -= nsR[7];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[8] += absSample; nsR[8] /= 2; absSample -= nsR[8];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[9] += absSample; nsR[9] /= 2; absSample -= nsR[9];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[10] += absSample; nsR[10] /= 2; absSample -= nsR[10];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[11] += absSample; nsR[11] /= 2; absSample -= nsR[11];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[12] += absSample; nsR[12] /= 2; absSample -= nsR[12];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[13] += absSample; nsR[13] /= 2; absSample -= nsR[13];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[14] += absSample; nsR[14] /= 2; absSample -= nsR[14];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[15] += absSample; nsR[15] /= 2; absSample -= nsR[15];
//install noise and then shape it
absSample += inputSampleR;
if (NSOddR > 0) NSOddR -= 0.97;
if (NSOddR < 0) NSOddR += 0.97;
NSOddR -= (NSOddR * NSOddR * NSOddR * 0.475);
NSOddR += prevR;
absSample += (NSOddR*0.475);
prevR = floor(absSample) - inputSampleR;
inputSampleR = floor(absSample);
//TenNines dither R
break;
case 9:
if (inputSampleL > 0) inputSampleL += 0.383;
if (inputSampleL < 0) inputSampleL -= 0.383;
if (inputSampleR > 0) inputSampleR += 0.383;
if (inputSampleR < 0) inputSampleR -= 0.383;
//adjusting to permit more information drug outta the noisefloor
contingentRnd = (((rand()/(double)RAND_MAX)+(rand()/(double)RAND_MAX))-1.0) * randyConstant; //produce TPDF dist, scale
contingentRnd -= contingentErrL*omegaConstant; //include err
absSample = fabs(inputSampleL);
contingentErrL = absSample - floor(absSample); //get next err
contingent = contingentErrL * 2.0; //scale of quantization levels
if (contingent > 1.0) contingent = ((-contingent+2.0)*omegaConstant) + expConstant;
else contingent = (contingent * omegaConstant) + expConstant;
//zero is next to a quantization level, one is exactly between them
if (flip) contingentRnd = (contingentRnd * (1.0-contingent)) + contingent + 0.5;
else contingentRnd = (contingentRnd * (1.0-contingent)) - contingent + 0.5;
inputSampleL += (contingentRnd * contingent);
//Contingent Dither
inputSampleL = floor(inputSampleL);
contingentRnd = (((rand()/(double)RAND_MAX)+(rand()/(double)RAND_MAX))-1.0) * randyConstant; //produce TPDF dist, scale
contingentRnd -= contingentErrR*omegaConstant; //include err
absSample = fabs(inputSampleR);
contingentErrR = absSample - floor(absSample); //get next err
contingent = contingentErrR * 2.0; //scale of quantization levels
if (contingent > 1.0) contingent = ((-contingent+2.0)*omegaConstant) + expConstant;
else contingent = (contingent * omegaConstant) + expConstant;
//zero is next to a quantization level, one is exactly between them
if (flip) contingentRnd = (contingentRnd * (1.0-contingent)) + contingent + 0.5;
else contingentRnd = (contingentRnd * (1.0-contingent)) - contingent + 0.5;
inputSampleR += (contingentRnd * contingent);
//Contingent Dither
inputSampleR = floor(inputSampleR);
//note: this does not dither for values exactly the same as 16 bit values-
//which forces the dither to gate at 0.0. It goes to digital black,
//and does a teeny parallel-compression thing when almost at digital black.
break;
case 10: //this one is the original Naturalize
if (inputSampleL > 0) inputSampleL += (0.3333333333);
if (inputSampleL < 0) inputSampleL -= (0.3333333333);
inputSampleL += (rand()/(double)RAND_MAX)*0.6666666666;
if (inputSampleR > 0) inputSampleR += (0.3333333333);
if (inputSampleR < 0) inputSampleR -= (0.3333333333);
inputSampleR += (rand()/(double)RAND_MAX)*0.6666666666;
//begin L
benfordize = floor(inputSampleL);
while (benfordize >= 1.0) {benfordize /= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
hotbinA = floor(benfordize);
//hotbin becomes the Benford bin value for this number floored
totalA = 0;
if ((hotbinA > 0) && (hotbinA < 10))
{
bynL[hotbinA] += 1;
totalA += (301-bynL[1]);
totalA += (176-bynL[2]);
totalA += (125-bynL[3]);
totalA += (97-bynL[4]);
totalA += (79-bynL[5]);
totalA += (67-bynL[6]);
totalA += (58-bynL[7]);
totalA += (51-bynL[8]);
totalA += (46-bynL[9]);
bynL[hotbinA] -= 1;
} else {hotbinA = 10;}
//produce total number- smaller is closer to Benford real
benfordize = ceil(inputSampleL);
while (benfordize >= 1.0) {benfordize /= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
hotbinB = floor(benfordize);
//hotbin becomes the Benford bin value for this number ceiled
totalB = 0;
if ((hotbinB > 0) && (hotbinB < 10))
{
bynL[hotbinB] += 1;
totalB += (301-bynL[1]);
totalB += (176-bynL[2]);
totalB += (125-bynL[3]);
totalB += (97-bynL[4]);
totalB += (79-bynL[5]);
totalB += (67-bynL[6]);
totalB += (58-bynL[7]);
totalB += (51-bynL[8]);
totalB += (46-bynL[9]);
bynL[hotbinB] -= 1;
} else {hotbinB = 10;}
//produce total number- smaller is closer to Benford real
if (totalA < totalB)
{
bynL[hotbinA] += 1;
inputSampleL = floor(inputSampleL);
}
else
{
bynL[hotbinB] += 1;
inputSampleL = ceil(inputSampleL);
}
//assign the relevant one to the delay line
//and floor/ceil signal accordingly
totalA = bynL[1] + bynL[2] + bynL[3] + bynL[4] + bynL[5] + bynL[6] + bynL[7] + bynL[8] + bynL[9];
totalA /= 1000;
if (totalA = 0) totalA = 1;
bynL[1] /= totalA;
bynL[2] /= totalA;
bynL[3] /= totalA;
bynL[4] /= totalA;
bynL[5] /= totalA;
bynL[6] /= totalA;
bynL[7] /= totalA;
bynL[8] /= totalA;
bynL[9] /= totalA;
bynL[10] /= 2; //catchall for garbage data
//end L
//begin R
benfordize = floor(inputSampleR);
while (benfordize >= 1.0) {benfordize /= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
hotbinA = floor(benfordize);
//hotbin becomes the Benford bin value for this number floored
totalA = 0;
if ((hotbinA > 0) && (hotbinA < 10))
{
bynR[hotbinA] += 1;
totalA += (301-bynR[1]);
totalA += (176-bynR[2]);
totalA += (125-bynR[3]);
totalA += (97-bynR[4]);
totalA += (79-bynR[5]);
totalA += (67-bynR[6]);
totalA += (58-bynR[7]);
totalA += (51-bynR[8]);
totalA += (46-bynR[9]);
bynR[hotbinA] -= 1;
} else {hotbinA = 10;}
//produce total number- smaller is closer to Benford real
benfordize = ceil(inputSampleR);
while (benfordize >= 1.0) {benfordize /= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
hotbinB = floor(benfordize);
//hotbin becomes the Benford bin value for this number ceiled
totalB = 0;
if ((hotbinB > 0) && (hotbinB < 10))
{
bynR[hotbinB] += 1;
totalB += (301-bynR[1]);
totalB += (176-bynR[2]);
totalB += (125-bynR[3]);
totalB += (97-bynR[4]);
totalB += (79-bynR[5]);
totalB += (67-bynR[6]);
totalB += (58-bynR[7]);
totalB += (51-bynR[8]);
totalB += (46-bynR[9]);
bynR[hotbinB] -= 1;
} else {hotbinB = 10;}
//produce total number- smaller is closer to Benford real
if (totalA < totalB)
{
bynR[hotbinA] += 1;
inputSampleR = floor(inputSampleR);
}
else
{
bynR[hotbinB] += 1;
inputSampleR = ceil(inputSampleR);
}
//assign the relevant one to the delay line
//and floor/ceil signal accordingly
totalA = bynR[1] + bynR[2] + bynR[3] + bynR[4] + bynR[5] + bynR[6] + bynR[7] + bynR[8] + bynR[9];
totalA /= 1000;
if (totalA = 0) totalA = 1;
bynR[1] /= totalA;
bynR[2] /= totalA;
bynR[3] /= totalA;
bynR[4] /= totalA;
bynR[5] /= totalA;
bynR[6] /= totalA;
bynR[7] /= totalA;
bynR[8] /= totalA;
bynR[9] /= totalA;
bynR[10] /= 2; //catchall for garbage data
//end R
break;
case 11: //this one is the Not Just Another Dither
//begin L
benfordize = floor(inputSampleL);
while (benfordize >= 1.0) {benfordize /= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
hotbinA = floor(benfordize);
//hotbin becomes the Benford bin value for this number floored
totalA = 0;
if ((hotbinA > 0) && (hotbinA < 10))
{
bynL[hotbinA] += 1;
totalA += (301-bynL[1]);
totalA += (176-bynL[2]);
totalA += (125-bynL[3]);
totalA += (97-bynL[4]);
totalA += (79-bynL[5]);
totalA += (67-bynL[6]);
totalA += (58-bynL[7]);
totalA += (51-bynL[8]);
totalA += (46-bynL[9]);
bynL[hotbinA] -= 1;
} else {hotbinA = 10;}
//produce total number- smaller is closer to Benford real
benfordize = ceil(inputSampleL);
while (benfordize >= 1.0) {benfordize /= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
hotbinB = floor(benfordize);
//hotbin becomes the Benford bin value for this number ceiled
totalB = 0;
if ((hotbinB > 0) && (hotbinB < 10))
{
bynL[hotbinB] += 1;
totalB += (301-bynL[1]);
totalB += (176-bynL[2]);
totalB += (125-bynL[3]);
totalB += (97-bynL[4]);
totalB += (79-bynL[5]);
totalB += (67-bynL[6]);
totalB += (58-bynL[7]);
totalB += (51-bynL[8]);
totalB += (46-bynL[9]);
bynL[hotbinB] -= 1;
} else {hotbinB = 10;}
//produce total number- smaller is closer to Benford real
if (totalA < totalB)
{
bynL[hotbinA] += 1;
inputSampleL = floor(inputSampleL);
}
else
{
bynL[hotbinB] += 1;
inputSampleL = ceil(inputSampleL);
}
//assign the relevant one to the delay line
//and floor/ceil signal accordingly
totalA = bynL[1] + bynL[2] + bynL[3] + bynL[4] + bynL[5] + bynL[6] + bynL[7] + bynL[8] + bynL[9];
totalA /= 1000;
if (totalA = 0) totalA = 1;
bynL[1] /= totalA;
bynL[2] /= totalA;
bynL[3] /= totalA;
bynL[4] /= totalA;
bynL[5] /= totalA;
bynL[6] /= totalA;
bynL[7] /= totalA;
bynL[8] /= totalA;
bynL[9] /= totalA;
bynL[10] /= 2; //catchall for garbage data
//end L
//begin R
benfordize = floor(inputSampleR);
while (benfordize >= 1.0) {benfordize /= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
hotbinA = floor(benfordize);
//hotbin becomes the Benford bin value for this number floored
totalA = 0;
if ((hotbinA > 0) && (hotbinA < 10))
{
bynR[hotbinA] += 1;
totalA += (301-bynR[1]);
totalA += (176-bynR[2]);
totalA += (125-bynR[3]);
totalA += (97-bynR[4]);
totalA += (79-bynR[5]);
totalA += (67-bynR[6]);
totalA += (58-bynR[7]);
totalA += (51-bynR[8]);
totalA += (46-bynR[9]);
bynR[hotbinA] -= 1;
} else {hotbinA = 10;}
//produce total number- smaller is closer to Benford real
benfordize = ceil(inputSampleR);
while (benfordize >= 1.0) {benfordize /= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
hotbinB = floor(benfordize);
//hotbin becomes the Benford bin value for this number ceiled
totalB = 0;
if ((hotbinB > 0) && (hotbinB < 10))
{
bynR[hotbinB] += 1;
totalB += (301-bynR[1]);
totalB += (176-bynR[2]);
totalB += (125-bynR[3]);
totalB += (97-bynR[4]);
totalB += (79-bynR[5]);
totalB += (67-bynR[6]);
totalB += (58-bynR[7]);
totalB += (51-bynR[8]);
totalB += (46-bynR[9]);
bynR[hotbinB] -= 1;
} else {hotbinB = 10;}
//produce total number- smaller is closer to Benford real
if (totalA < totalB)
{
bynR[hotbinA] += 1;
inputSampleR = floor(inputSampleR);
}
else
{
bynR[hotbinB] += 1;
inputSampleR = ceil(inputSampleR);
}
//assign the relevant one to the delay line
//and floor/ceil signal accordingly
totalA = bynR[1] + bynR[2] + bynR[3] + bynR[4] + bynR[5] + bynR[6] + bynR[7] + bynR[8] + bynR[9];
totalA /= 1000;
if (totalA = 0) totalA = 1;
bynR[1] /= totalA;
bynR[2] /= totalA;
bynR[3] /= totalA;
bynR[4] /= totalA;
bynR[5] /= totalA;
bynR[6] /= totalA;
bynR[7] /= totalA;
bynR[8] /= totalA;
bynR[9] /= totalA;
bynR[10] /= 2; //catchall for garbage data
//end R
break;
case 12:
//slew only
outputSampleL = (inputSampleL - lastSampleL)*trim;
outputSampleR = (inputSampleR - lastSampleR)*trim;
lastSampleL = inputSampleL;
lastSampleR = inputSampleR;
if (outputSampleL > 1.0) outputSampleL = 1.0;
if (outputSampleR > 1.0) outputSampleR = 1.0;
if (outputSampleL < -1.0) outputSampleL = -1.0;
if (outputSampleR < -1.0) outputSampleR = -1.0;
inputSampleL = outputSampleL;
inputSampleR = outputSampleR;
break;
case 13:
//subs only
gain = gaintarget;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
iirSampleAL = (iirSampleAL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleAL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleBL = (iirSampleBL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleBL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleCL = (iirSampleCL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleCL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleDL = (iirSampleDL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleDL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleEL = (iirSampleEL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleEL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleFL = (iirSampleFL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleFL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleGL = (iirSampleGL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleGL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleHL = (iirSampleHL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleHL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleIL = (iirSampleIL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleIL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleJL = (iirSampleJL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleJL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleKL = (iirSampleKL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleKL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleLL = (iirSampleLL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleLL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleML = (iirSampleML * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleML;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleNL = (iirSampleNL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleNL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleOL = (iirSampleOL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleOL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSamplePL = (iirSamplePL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSamplePL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleQL = (iirSampleQL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleQL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleRL = (iirSampleRL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleRL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleSL = (iirSampleSL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleSL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleTL = (iirSampleTL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleTL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleUL = (iirSampleUL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleUL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleVL = (iirSampleVL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleVL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleWL = (iirSampleWL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleWL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleXL = (iirSampleXL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleXL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleYL = (iirSampleYL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleYL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleZL = (iirSampleZL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleZL;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
gain = gaintarget;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
iirSampleAR = (iirSampleAR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleAR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleBR = (iirSampleBR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleBR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleCR = (iirSampleCR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleCR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleDR = (iirSampleDR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleDR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleER = (iirSampleER * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleER;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleFR = (iirSampleFR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleFR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleGR = (iirSampleGR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleGR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleHR = (iirSampleHR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleHR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleIR = (iirSampleIR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleIR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleJR = (iirSampleJR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleJR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleKR = (iirSampleKR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleKR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleLR = (iirSampleLR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleLR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleMR = (iirSampleMR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleMR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleNR = (iirSampleNR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleNR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleOR = (iirSampleOR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleOR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSamplePR = (iirSamplePR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSamplePR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleQR = (iirSampleQR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleQR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleRR = (iirSampleRR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleRR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleSR = (iirSampleSR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleSR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleTR = (iirSampleTR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleTR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleUR = (iirSampleUR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleUR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleVR = (iirSampleVR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleVR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleWR = (iirSampleWR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleWR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleXR = (iirSampleXR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleXR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleYR = (iirSampleYR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleYR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleZR = (iirSampleZR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleZR;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
break;
case 14:
//silhouette
//begin L
bridgerectifier = fabs(inputSampleL)*1.57079633;
if (bridgerectifier > 1.57079633) bridgerectifier = 1.57079633;
bridgerectifier = 1.0-cos(bridgerectifier);
if (inputSampleL > 0.0) inputSampleL = bridgerectifier;
else inputSampleL = -bridgerectifier;
silhouette = rand()/(double)RAND_MAX;
silhouette -= 0.5;
silhouette *= 2.0;
silhouette *= fabs(inputSampleL);
smoother = rand()/(double)RAND_MAX;
smoother -= 0.5;
smoother *= 2.0;
smoother *= fabs(lastSampleL);
lastSampleL = inputSampleL;
silhouette += smoother;
bridgerectifier = fabs(silhouette)*1.57079633;
if (bridgerectifier > 1.57079633) bridgerectifier = 1.57079633;
bridgerectifier = sin(bridgerectifier);
if (silhouette > 0.0) silhouette = bridgerectifier;
else silhouette = -bridgerectifier;
inputSampleL = (silhouette + outSampleL) / 2.0;
outSampleL = silhouette;
//end L
//begin R
bridgerectifier = fabs(inputSampleR)*1.57079633;
if (bridgerectifier > 1.57079633) bridgerectifier = 1.57079633;
bridgerectifier = 1.0-cos(bridgerectifier);
if (inputSampleR > 0.0) inputSampleR = bridgerectifier;
else inputSampleR = -bridgerectifier;
silhouette = rand()/(double)RAND_MAX;
silhouette -= 0.5;
silhouette *= 2.0;
silhouette *= fabs(inputSampleR);
smoother = rand()/(double)RAND_MAX;
smoother -= 0.5;
smoother *= 2.0;
smoother *= fabs(lastSampleR);
lastSampleR = inputSampleR;
silhouette += smoother;
bridgerectifier = fabs(silhouette)*1.57079633;
if (bridgerectifier > 1.57079633) bridgerectifier = 1.57079633;
bridgerectifier = sin(bridgerectifier);
if (silhouette > 0.0) silhouette = bridgerectifier;
else silhouette = -bridgerectifier;
inputSampleR = (silhouette + outSampleR) / 2.0;
outSampleR = silhouette;
//end R
break;
}
flip = !flip;
//several dithers use this
if (highRes) {inputSampleL /= 256.0; inputSampleR /= 256.0;} //256 for 16/24 version
if (dithering) {inputSampleL /= 32768.0; inputSampleR /= 32768.0;}
if (dtype == 8) {
noiseShapingL += inputSampleL - drySampleL;
noiseShapingR += inputSampleR - drySampleR;
}
*out1 = inputSampleL;
*out2 = inputSampleR;
*in1++;
*in2++;
*out1++;
*out2++;
}
}
void Ditherbox::processDoubleReplacing(double **inputs, double **outputs, VstInt32 sampleFrames)
{
double* in1 = inputs[0];
double* in2 = inputs[1];
double* out1 = outputs[0];
double* out2 = outputs[1];
int dtype = (int)(A * 24.999)+1; // +1 for Reaper bug workaround
long double overallscale = 1.0;
overallscale /= 44100.0;
overallscale *= getSampleRate();
long double iirAmount = 2250/44100.0;
long double gaintarget = 1.42;
long double gain;
iirAmount /= overallscale;
long double altAmount = 1.0 - iirAmount;
long double outputSampleL;
long double outputSampleR;
long double silhouette;
long double smoother;
long double bridgerectifier;
long double benfordize;
int hotbinA;
int hotbinB;
long double totalA;
long double totalB;
long double contingentRnd;
long double absSample;
long double contingent;
long double randyConstant = 1.61803398874989484820458683436563811772030917980576;
long double omegaConstant = 0.56714329040978387299996866221035554975381578718651;
long double expConstant = 0.06598803584531253707679018759684642493857704825279;
long double trim = 2.302585092994045684017991; //natural logarithm of 10
bool highRes = false;
bool dithering = true;
if (dtype > 11){highRes = true; dtype -= 11;}
if (dtype > 11){dithering = false; highRes = false;}
//follow up by switching high res back off for the monitoring
while (--sampleFrames >= 0)
{
long double inputSampleL = *in1;
long double inputSampleR = *in2;
if (inputSampleL<1.2e-38 && -inputSampleL<1.2e-38) {
static int noisesource = 0;
//this declares a variable before anything else is compiled. It won't keep assigning
//it to 0 for every sample, it's as if the declaration doesn't exist in this context,
//but it lets me add this denormalization fix in a single place rather than updating
//it in three different locations. The variable isn't thread-safe but this is only
//a random seed and we can share it with whatever.
noisesource = noisesource % 1700021; noisesource++;
int residue = noisesource * noisesource;
residue = residue % 170003; residue *= residue;
residue = residue % 17011; residue *= residue;
residue = residue % 1709; residue *= residue;
residue = residue % 173; residue *= residue;
residue = residue % 17;
double applyresidue = residue;
applyresidue *= 0.00000001;
applyresidue *= 0.00000001;
inputSampleL = applyresidue;
}
if (inputSampleR<1.2e-38 && -inputSampleR<1.2e-38) {
static int noisesource = 0;
noisesource = noisesource % 1700021; noisesource++;
int residue = noisesource * noisesource;
residue = residue % 170003; residue *= residue;
residue = residue % 17011; residue *= residue;
residue = residue % 1709; residue *= residue;
residue = residue % 173; residue *= residue;
residue = residue % 17;
double applyresidue = residue;
applyresidue *= 0.00000001;
applyresidue *= 0.00000001;
inputSampleR = applyresidue;
//this denormalization routine produces a white noise at -300 dB which the noise
//shaping will interact with to produce a bipolar output, but the noise is actually
//all positive. That should stop any variables from going denormal, and the routine
//only kicks in if digital black is input. As a final touch, if you save to 24-bit
//the silence will return to being digital black again.
}
double drySampleL = inputSampleL;
double drySampleR = inputSampleR;
if (dtype == 8) {inputSampleL -= noiseShapingL; inputSampleR -= noiseShapingR;}
if (dithering) {inputSampleL *= 32768.0; inputSampleR *= 32768.0;}
//denormalizing as way of controlling insane detail boosting
if (highRes) {inputSampleL *= 256.0; inputSampleR *= 256.0;} //256 for 16/24 version
switch (dtype)
{
case 1:
inputSampleL = floor(inputSampleL);
inputSampleR = floor(inputSampleR);
//truncate
break;
case 2:
inputSampleL += (rand()/(double)RAND_MAX);
inputSampleL -= 0.5;
inputSampleL = floor(inputSampleL);
inputSampleR += (rand()/(double)RAND_MAX);
inputSampleR -= 0.5;
inputSampleR = floor(inputSampleR);
//flat dither
break;
case 3:
inputSampleL += (rand()/(double)RAND_MAX);
inputSampleL += (rand()/(double)RAND_MAX);
inputSampleL -= 1.0;
inputSampleL = floor(inputSampleL);
inputSampleR += (rand()/(double)RAND_MAX);
inputSampleR += (rand()/(double)RAND_MAX);
inputSampleR -= 1.0;
inputSampleR = floor(inputSampleR);
//TPDF dither
break;
case 4:
currentDitherL = (rand()/(double)RAND_MAX);
inputSampleL += currentDitherL;
inputSampleL -= lastSampleL;
inputSampleL = floor(inputSampleL);
lastSampleL = currentDitherL;
currentDitherR = (rand()/(double)RAND_MAX);
inputSampleR += currentDitherR;
inputSampleR -= lastSampleR;
inputSampleR = floor(inputSampleR);
lastSampleR = currentDitherR;
//Paul dither
break;
case 5:
nsL[9] = nsL[8]; nsL[8] = nsL[7]; nsL[7] = nsL[6]; nsL[6] = nsL[5];
nsL[5] = nsL[4]; nsL[4] = nsL[3]; nsL[3] = nsL[2]; nsL[2] = nsL[1];
nsL[1] = nsL[0]; nsL[0] = (rand()/(double)RAND_MAX);
currentDitherL = (nsL[0] * 0.061);
currentDitherL -= (nsL[1] * 0.11);
currentDitherL += (nsL[8] * 0.126);
currentDitherL -= (nsL[7] * 0.23);
currentDitherL += (nsL[2] * 0.25);
currentDitherL -= (nsL[3] * 0.43);
currentDitherL += (nsL[6] * 0.5);
currentDitherL -= nsL[5];
currentDitherL += nsL[4];
//this sounds different from doing it in order of sample position
//cumulative tiny errors seem to build up even at this buss depth
//considerably more pronounced at 32 bit float.
//Therefore we add the most significant components LAST.
//trying to keep values on like exponents of the floating point value.
inputSampleL += currentDitherL;
inputSampleL = floor(inputSampleL);
//done with L
nsR[9] = nsR[8]; nsR[8] = nsR[7]; nsR[7] = nsR[6]; nsR[6] = nsR[5];
nsR[5] = nsR[4]; nsR[4] = nsR[3]; nsR[3] = nsR[2]; nsR[2] = nsR[1];
nsR[1] = nsR[0]; nsR[0] = (rand()/(double)RAND_MAX);
currentDitherR = (nsR[0] * 0.061);
currentDitherR -= (nsR[1] * 0.11);
currentDitherR += (nsR[8] * 0.126);
currentDitherR -= (nsR[7] * 0.23);
currentDitherR += (nsR[2] * 0.25);
currentDitherR -= (nsR[3] * 0.43);
currentDitherR += (nsR[6] * 0.5);
currentDitherR -= nsR[5];
currentDitherR += nsR[4];
//this sounds different from doing it in order of sample position
//cumulative tiny errors seem to build up even at this buss depth
//considerably more pronounced at 32 bit float.
//Therefore we add the most significant components LAST.
//trying to keep values on like exponents of the floating point value.
inputSampleR += currentDitherR;
inputSampleR = floor(inputSampleR);
//done with R
//DoublePaul dither
break;
case 6:
currentDitherL = (rand()/(double)RAND_MAX);
currentDitherR = (rand()/(double)RAND_MAX);
inputSampleL += currentDitherL;
inputSampleR += currentDitherR;
inputSampleL -= nsL[4];
inputSampleR -= nsR[4];
inputSampleL = floor(inputSampleL);
inputSampleR = floor(inputSampleR);
nsL[4] = nsL[3];
nsL[3] = nsL[2];
nsL[2] = nsL[1];
nsL[1] = currentDitherL;
nsR[4] = nsR[3];
nsR[3] = nsR[2];
nsR[2] = nsR[1];
nsR[1] = currentDitherR;
//Tape dither
break;
case 7:
Position += 1;
//Note- uses integer overflow as a 'mod' operator
hotbinA = Position * Position;
hotbinA = hotbinA % 170003; //% is C++ mod operator
hotbinA *= hotbinA;
hotbinA = hotbinA % 17011; //% is C++ mod operator
hotbinA *= hotbinA;
hotbinA = hotbinA % 1709; //% is C++ mod operator
hotbinA *= hotbinA;
hotbinA = hotbinA % 173; //% is C++ mod operator
hotbinA *= hotbinA;
hotbinA = hotbinA % 17;
hotbinA *= 0.0635;
if (flip) hotbinA = -hotbinA;
inputSampleL += hotbinA;
inputSampleR += hotbinA;
inputSampleL = floor(inputSampleL);
inputSampleR = floor(inputSampleR);
//Quadratic dither
break;
case 8:
absSample = ((rand()/(double)RAND_MAX) - 0.5);
nsL[0] += absSample; nsL[0] /= 2; absSample -= nsL[0];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[1] += absSample; nsL[1] /= 2; absSample -= nsL[1];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[2] += absSample; nsL[2] /= 2; absSample -= nsL[2];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[3] += absSample; nsL[3] /= 2; absSample -= nsL[3];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[4] += absSample; nsL[4] /= 2; absSample -= nsL[4];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[5] += absSample; nsL[5] /= 2; absSample -= nsL[5];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[6] += absSample; nsL[6] /= 2; absSample -= nsL[6];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[7] += absSample; nsL[7] /= 2; absSample -= nsL[7];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[8] += absSample; nsL[8] /= 2; absSample -= nsL[8];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[9] += absSample; nsL[9] /= 2; absSample -= nsL[9];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[10] += absSample; nsL[10] /= 2; absSample -= nsL[10];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[11] += absSample; nsL[11] /= 2; absSample -= nsL[11];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[12] += absSample; nsL[12] /= 2; absSample -= nsL[12];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[13] += absSample; nsL[13] /= 2; absSample -= nsL[13];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[14] += absSample; nsL[14] /= 2; absSample -= nsL[14];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[15] += absSample; nsL[15] /= 2; absSample -= nsL[15];
//install noise and then shape it
absSample += inputSampleL;
if (NSOddL > 0) NSOddL -= 0.97;
if (NSOddL < 0) NSOddL += 0.97;
NSOddL -= (NSOddL * NSOddL * NSOddL * 0.475);
NSOddL += prevL;
absSample += (NSOddL*0.475);
prevL = floor(absSample) - inputSampleL;
inputSampleL = floor(absSample);
//TenNines dither L
absSample = ((rand()/(double)RAND_MAX) - 0.5);
nsR[0] += absSample; nsR[0] /= 2; absSample -= nsR[0];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[1] += absSample; nsR[1] /= 2; absSample -= nsR[1];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[2] += absSample; nsR[2] /= 2; absSample -= nsR[2];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[3] += absSample; nsR[3] /= 2; absSample -= nsR[3];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[4] += absSample; nsR[4] /= 2; absSample -= nsR[4];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[5] += absSample; nsR[5] /= 2; absSample -= nsR[5];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[6] += absSample; nsR[6] /= 2; absSample -= nsR[6];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[7] += absSample; nsR[7] /= 2; absSample -= nsR[7];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[8] += absSample; nsR[8] /= 2; absSample -= nsR[8];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[9] += absSample; nsR[9] /= 2; absSample -= nsR[9];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[10] += absSample; nsR[10] /= 2; absSample -= nsR[10];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[11] += absSample; nsR[11] /= 2; absSample -= nsR[11];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[12] += absSample; nsR[12] /= 2; absSample -= nsR[12];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[13] += absSample; nsR[13] /= 2; absSample -= nsR[13];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[14] += absSample; nsR[14] /= 2; absSample -= nsR[14];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[15] += absSample; nsR[15] /= 2; absSample -= nsR[15];
//install noise and then shape it
absSample += inputSampleR;
if (NSOddR > 0) NSOddR -= 0.97;
if (NSOddR < 0) NSOddR += 0.97;
NSOddR -= (NSOddR * NSOddR * NSOddR * 0.475);
NSOddR += prevR;
absSample += (NSOddR*0.475);
prevR = floor(absSample) - inputSampleR;
inputSampleR = floor(absSample);
//TenNines dither R
break;
case 9:
if (inputSampleL > 0) inputSampleL += 0.383;
if (inputSampleL < 0) inputSampleL -= 0.383;
if (inputSampleR > 0) inputSampleR += 0.383;
if (inputSampleR < 0) inputSampleR -= 0.383;
//adjusting to permit more information drug outta the noisefloor
contingentRnd = (((rand()/(double)RAND_MAX)+(rand()/(double)RAND_MAX))-1.0) * randyConstant; //produce TPDF dist, scale
contingentRnd -= contingentErrL*omegaConstant; //include err
absSample = fabs(inputSampleL);
contingentErrL = absSample - floor(absSample); //get next err
contingent = contingentErrL * 2.0; //scale of quantization levels
if (contingent > 1.0) contingent = ((-contingent+2.0)*omegaConstant) + expConstant;
else contingent = (contingent * omegaConstant) + expConstant;
//zero is next to a quantization level, one is exactly between them
if (flip) contingentRnd = (contingentRnd * (1.0-contingent)) + contingent + 0.5;
else contingentRnd = (contingentRnd * (1.0-contingent)) - contingent + 0.5;
inputSampleL += (contingentRnd * contingent);
//Contingent Dither
inputSampleL = floor(inputSampleL);
contingentRnd = (((rand()/(double)RAND_MAX)+(rand()/(double)RAND_MAX))-1.0) * randyConstant; //produce TPDF dist, scale
contingentRnd -= contingentErrR*omegaConstant; //include err
absSample = fabs(inputSampleR);
contingentErrR = absSample - floor(absSample); //get next err
contingent = contingentErrR * 2.0; //scale of quantization levels
if (contingent > 1.0) contingent = ((-contingent+2.0)*omegaConstant) + expConstant;
else contingent = (contingent * omegaConstant) + expConstant;
//zero is next to a quantization level, one is exactly between them
if (flip) contingentRnd = (contingentRnd * (1.0-contingent)) + contingent + 0.5;
else contingentRnd = (contingentRnd * (1.0-contingent)) - contingent + 0.5;
inputSampleR += (contingentRnd * contingent);
//Contingent Dither
inputSampleR = floor(inputSampleR);
//note: this does not dither for values exactly the same as 16 bit values-
//which forces the dither to gate at 0.0. It goes to digital black,
//and does a teeny parallel-compression thing when almost at digital black.
break;
case 10: //this one is the original Naturalize
if (inputSampleL > 0) inputSampleL += (0.3333333333);
if (inputSampleL < 0) inputSampleL -= (0.3333333333);
inputSampleL += (rand()/(double)RAND_MAX)*0.6666666666;
if (inputSampleR > 0) inputSampleR += (0.3333333333);
if (inputSampleR < 0) inputSampleR -= (0.3333333333);
inputSampleR += (rand()/(double)RAND_MAX)*0.6666666666;
//begin L
benfordize = floor(inputSampleL);
while (benfordize >= 1.0) {benfordize /= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
hotbinA = floor(benfordize);
//hotbin becomes the Benford bin value for this number floored
totalA = 0;
if ((hotbinA > 0) && (hotbinA < 10))
{
bynL[hotbinA] += 1;
totalA += (301-bynL[1]);
totalA += (176-bynL[2]);
totalA += (125-bynL[3]);
totalA += (97-bynL[4]);
totalA += (79-bynL[5]);
totalA += (67-bynL[6]);
totalA += (58-bynL[7]);
totalA += (51-bynL[8]);
totalA += (46-bynL[9]);
bynL[hotbinA] -= 1;
} else {hotbinA = 10;}
//produce total number- smaller is closer to Benford real
benfordize = ceil(inputSampleL);
while (benfordize >= 1.0) {benfordize /= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
hotbinB = floor(benfordize);
//hotbin becomes the Benford bin value for this number ceiled
totalB = 0;
if ((hotbinB > 0) && (hotbinB < 10))
{
bynL[hotbinB] += 1;
totalB += (301-bynL[1]);
totalB += (176-bynL[2]);
totalB += (125-bynL[3]);
totalB += (97-bynL[4]);
totalB += (79-bynL[5]);
totalB += (67-bynL[6]);
totalB += (58-bynL[7]);
totalB += (51-bynL[8]);
totalB += (46-bynL[9]);
bynL[hotbinB] -= 1;
} else {hotbinB = 10;}
//produce total number- smaller is closer to Benford real
if (totalA < totalB)
{
bynL[hotbinA] += 1;
inputSampleL = floor(inputSampleL);
}
else
{
bynL[hotbinB] += 1;
inputSampleL = ceil(inputSampleL);
}
//assign the relevant one to the delay line
//and floor/ceil signal accordingly
totalA = bynL[1] + bynL[2] + bynL[3] + bynL[4] + bynL[5] + bynL[6] + bynL[7] + bynL[8] + bynL[9];
totalA /= 1000;
if (totalA = 0) totalA = 1;
bynL[1] /= totalA;
bynL[2] /= totalA;
bynL[3] /= totalA;
bynL[4] /= totalA;
bynL[5] /= totalA;
bynL[6] /= totalA;
bynL[7] /= totalA;
bynL[8] /= totalA;
bynL[9] /= totalA;
bynL[10] /= 2; //catchall for garbage data
//end L
//begin R
benfordize = floor(inputSampleR);
while (benfordize >= 1.0) {benfordize /= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
hotbinA = floor(benfordize);
//hotbin becomes the Benford bin value for this number floored
totalA = 0;
if ((hotbinA > 0) && (hotbinA < 10))
{
bynR[hotbinA] += 1;
totalA += (301-bynR[1]);
totalA += (176-bynR[2]);
totalA += (125-bynR[3]);
totalA += (97-bynR[4]);
totalA += (79-bynR[5]);
totalA += (67-bynR[6]);
totalA += (58-bynR[7]);
totalA += (51-bynR[8]);
totalA += (46-bynR[9]);
bynR[hotbinA] -= 1;
} else {hotbinA = 10;}
//produce total number- smaller is closer to Benford real
benfordize = ceil(inputSampleR);
while (benfordize >= 1.0) {benfordize /= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
hotbinB = floor(benfordize);
//hotbin becomes the Benford bin value for this number ceiled
totalB = 0;
if ((hotbinB > 0) && (hotbinB < 10))
{
bynR[hotbinB] += 1;
totalB += (301-bynR[1]);
totalB += (176-bynR[2]);
totalB += (125-bynR[3]);
totalB += (97-bynR[4]);
totalB += (79-bynR[5]);
totalB += (67-bynR[6]);
totalB += (58-bynR[7]);
totalB += (51-bynR[8]);
totalB += (46-bynR[9]);
bynR[hotbinB] -= 1;
} else {hotbinB = 10;}
//produce total number- smaller is closer to Benford real
if (totalA < totalB)
{
bynR[hotbinA] += 1;
inputSampleR = floor(inputSampleR);
}
else
{
bynR[hotbinB] += 1;
inputSampleR = ceil(inputSampleR);
}
//assign the relevant one to the delay line
//and floor/ceil signal accordingly
totalA = bynR[1] + bynR[2] + bynR[3] + bynR[4] + bynR[5] + bynR[6] + bynR[7] + bynR[8] + bynR[9];
totalA /= 1000;
if (totalA = 0) totalA = 1;
bynR[1] /= totalA;
bynR[2] /= totalA;
bynR[3] /= totalA;
bynR[4] /= totalA;
bynR[5] /= totalA;
bynR[6] /= totalA;
bynR[7] /= totalA;
bynR[8] /= totalA;
bynR[9] /= totalA;
bynR[10] /= 2; //catchall for garbage data
//end R
break;
case 11: //this one is the Not Just Another Dither
//begin L
benfordize = floor(inputSampleL);
while (benfordize >= 1.0) {benfordize /= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
hotbinA = floor(benfordize);
//hotbin becomes the Benford bin value for this number floored
totalA = 0;
if ((hotbinA > 0) && (hotbinA < 10))
{
bynL[hotbinA] += 1;
totalA += (301-bynL[1]);
totalA += (176-bynL[2]);
totalA += (125-bynL[3]);
totalA += (97-bynL[4]);
totalA += (79-bynL[5]);
totalA += (67-bynL[6]);
totalA += (58-bynL[7]);
totalA += (51-bynL[8]);
totalA += (46-bynL[9]);
bynL[hotbinA] -= 1;
} else {hotbinA = 10;}
//produce total number- smaller is closer to Benford real
benfordize = ceil(inputSampleL);
while (benfordize >= 1.0) {benfordize /= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
hotbinB = floor(benfordize);
//hotbin becomes the Benford bin value for this number ceiled
totalB = 0;
if ((hotbinB > 0) && (hotbinB < 10))
{
bynL[hotbinB] += 1;
totalB += (301-bynL[1]);
totalB += (176-bynL[2]);
totalB += (125-bynL[3]);
totalB += (97-bynL[4]);
totalB += (79-bynL[5]);
totalB += (67-bynL[6]);
totalB += (58-bynL[7]);
totalB += (51-bynL[8]);
totalB += (46-bynL[9]);
bynL[hotbinB] -= 1;
} else {hotbinB = 10;}
//produce total number- smaller is closer to Benford real
if (totalA < totalB)
{
bynL[hotbinA] += 1;
inputSampleL = floor(inputSampleL);
}
else
{
bynL[hotbinB] += 1;
inputSampleL = ceil(inputSampleL);
}
//assign the relevant one to the delay line
//and floor/ceil signal accordingly
totalA = bynL[1] + bynL[2] + bynL[3] + bynL[4] + bynL[5] + bynL[6] + bynL[7] + bynL[8] + bynL[9];
totalA /= 1000;
if (totalA = 0) totalA = 1;
bynL[1] /= totalA;
bynL[2] /= totalA;
bynL[3] /= totalA;
bynL[4] /= totalA;
bynL[5] /= totalA;
bynL[6] /= totalA;
bynL[7] /= totalA;
bynL[8] /= totalA;
bynL[9] /= totalA;
bynL[10] /= 2; //catchall for garbage data
//end L
//begin R
benfordize = floor(inputSampleR);
while (benfordize >= 1.0) {benfordize /= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
hotbinA = floor(benfordize);
//hotbin becomes the Benford bin value for this number floored
totalA = 0;
if ((hotbinA > 0) && (hotbinA < 10))
{
bynR[hotbinA] += 1;
totalA += (301-bynR[1]);
totalA += (176-bynR[2]);
totalA += (125-bynR[3]);
totalA += (97-bynR[4]);
totalA += (79-bynR[5]);
totalA += (67-bynR[6]);
totalA += (58-bynR[7]);
totalA += (51-bynR[8]);
totalA += (46-bynR[9]);
bynR[hotbinA] -= 1;
} else {hotbinA = 10;}
//produce total number- smaller is closer to Benford real
benfordize = ceil(inputSampleR);
while (benfordize >= 1.0) {benfordize /= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
if (benfordize < 1.0) {benfordize *= 10;}
hotbinB = floor(benfordize);
//hotbin becomes the Benford bin value for this number ceiled
totalB = 0;
if ((hotbinB > 0) && (hotbinB < 10))
{
bynR[hotbinB] += 1;
totalB += (301-bynR[1]);
totalB += (176-bynR[2]);
totalB += (125-bynR[3]);
totalB += (97-bynR[4]);
totalB += (79-bynR[5]);
totalB += (67-bynR[6]);
totalB += (58-bynR[7]);
totalB += (51-bynR[8]);
totalB += (46-bynR[9]);
bynR[hotbinB] -= 1;
} else {hotbinB = 10;}
//produce total number- smaller is closer to Benford real
if (totalA < totalB)
{
bynR[hotbinA] += 1;
inputSampleR = floor(inputSampleR);
}
else
{
bynR[hotbinB] += 1;
inputSampleR = ceil(inputSampleR);
}
//assign the relevant one to the delay line
//and floor/ceil signal accordingly
totalA = bynR[1] + bynR[2] + bynR[3] + bynR[4] + bynR[5] + bynR[6] + bynR[7] + bynR[8] + bynR[9];
totalA /= 1000;
if (totalA = 0) totalA = 1;
bynR[1] /= totalA;
bynR[2] /= totalA;
bynR[3] /= totalA;
bynR[4] /= totalA;
bynR[5] /= totalA;
bynR[6] /= totalA;
bynR[7] /= totalA;
bynR[8] /= totalA;
bynR[9] /= totalA;
bynR[10] /= 2; //catchall for garbage data
//end R
break;
case 12:
//slew only
outputSampleL = (inputSampleL - lastSampleL)*trim;
outputSampleR = (inputSampleR - lastSampleR)*trim;
lastSampleL = inputSampleL;
lastSampleR = inputSampleR;
if (outputSampleL > 1.0) outputSampleL = 1.0;
if (outputSampleR > 1.0) outputSampleR = 1.0;
if (outputSampleL < -1.0) outputSampleL = -1.0;
if (outputSampleR < -1.0) outputSampleR = -1.0;
inputSampleL = outputSampleL;
inputSampleR = outputSampleR;
break;
case 13:
//subs only
gain = gaintarget;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
iirSampleAL = (iirSampleAL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleAL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleBL = (iirSampleBL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleBL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleCL = (iirSampleCL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleCL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleDL = (iirSampleDL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleDL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleEL = (iirSampleEL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleEL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleFL = (iirSampleFL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleFL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleGL = (iirSampleGL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleGL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleHL = (iirSampleHL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleHL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleIL = (iirSampleIL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleIL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleJL = (iirSampleJL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleJL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleKL = (iirSampleKL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleKL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleLL = (iirSampleLL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleLL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleML = (iirSampleML * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleML;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleNL = (iirSampleNL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleNL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleOL = (iirSampleOL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleOL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSamplePL = (iirSamplePL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSamplePL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleQL = (iirSampleQL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleQL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleRL = (iirSampleRL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleRL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleSL = (iirSampleSL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleSL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleTL = (iirSampleTL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleTL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleUL = (iirSampleUL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleUL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleVL = (iirSampleVL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleVL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleWL = (iirSampleWL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleWL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleXL = (iirSampleXL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleXL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleYL = (iirSampleYL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleYL;
inputSampleL *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
iirSampleZL = (iirSampleZL * altAmount) + (inputSampleL * iirAmount); inputSampleL = iirSampleZL;
if (inputSampleL > 1.0) inputSampleL = 1.0;
if (inputSampleL < -1.0) inputSampleL = -1.0;
gain = gaintarget;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
iirSampleAR = (iirSampleAR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleAR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleBR = (iirSampleBR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleBR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleCR = (iirSampleCR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleCR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleDR = (iirSampleDR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleDR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleER = (iirSampleER * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleER;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleFR = (iirSampleFR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleFR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleGR = (iirSampleGR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleGR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleHR = (iirSampleHR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleHR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleIR = (iirSampleIR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleIR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleJR = (iirSampleJR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleJR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleKR = (iirSampleKR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleKR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleLR = (iirSampleLR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleLR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleMR = (iirSampleMR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleMR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleNR = (iirSampleNR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleNR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleOR = (iirSampleOR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleOR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSamplePR = (iirSamplePR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSamplePR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleQR = (iirSampleQR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleQR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleRR = (iirSampleRR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleRR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleSR = (iirSampleSR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleSR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleTR = (iirSampleTR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleTR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleUR = (iirSampleUR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleUR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleVR = (iirSampleVR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleVR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleWR = (iirSampleWR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleWR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleXR = (iirSampleXR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleXR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleYR = (iirSampleYR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleYR;
inputSampleR *= gain; gain = ((gain-1)*0.75)+1;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
iirSampleZR = (iirSampleZR * altAmount) + (inputSampleR * iirAmount); inputSampleR = iirSampleZR;
if (inputSampleR > 1.0) inputSampleR = 1.0;
if (inputSampleR < -1.0) inputSampleR = -1.0;
break;
case 14:
//silhouette
//begin L
bridgerectifier = fabs(inputSampleL)*1.57079633;
if (bridgerectifier > 1.57079633) bridgerectifier = 1.57079633;
bridgerectifier = 1.0-cos(bridgerectifier);
if (inputSampleL > 0.0) inputSampleL = bridgerectifier;
else inputSampleL = -bridgerectifier;
silhouette = rand()/(double)RAND_MAX;
silhouette -= 0.5;
silhouette *= 2.0;
silhouette *= fabs(inputSampleL);
smoother = rand()/(double)RAND_MAX;
smoother -= 0.5;
smoother *= 2.0;
smoother *= fabs(lastSampleL);
lastSampleL = inputSampleL;
silhouette += smoother;
bridgerectifier = fabs(silhouette)*1.57079633;
if (bridgerectifier > 1.57079633) bridgerectifier = 1.57079633;
bridgerectifier = sin(bridgerectifier);
if (silhouette > 0.0) silhouette = bridgerectifier;
else silhouette = -bridgerectifier;
inputSampleL = (silhouette + outSampleL) / 2.0;
outSampleL = silhouette;
//end L
//begin R
bridgerectifier = fabs(inputSampleR)*1.57079633;
if (bridgerectifier > 1.57079633) bridgerectifier = 1.57079633;
bridgerectifier = 1.0-cos(bridgerectifier);
if (inputSampleR > 0.0) inputSampleR = bridgerectifier;
else inputSampleR = -bridgerectifier;
silhouette = rand()/(double)RAND_MAX;
silhouette -= 0.5;
silhouette *= 2.0;
silhouette *= fabs(inputSampleR);
smoother = rand()/(double)RAND_MAX;
smoother -= 0.5;
smoother *= 2.0;
smoother *= fabs(lastSampleR);
lastSampleR = inputSampleR;
silhouette += smoother;
bridgerectifier = fabs(silhouette)*1.57079633;
if (bridgerectifier > 1.57079633) bridgerectifier = 1.57079633;
bridgerectifier = sin(bridgerectifier);
if (silhouette > 0.0) silhouette = bridgerectifier;
else silhouette = -bridgerectifier;
inputSampleR = (silhouette + outSampleR) / 2.0;
outSampleR = silhouette;
//end R
break;
}
flip = !flip;
//several dithers use this
if (highRes) {inputSampleL /= 256.0; inputSampleR /= 256.0;} //256 for 16/24 version
if (dithering) {inputSampleL /= 32768.0; inputSampleR /= 32768.0;}
if (dtype == 8) {
noiseShapingL += inputSampleL - drySampleL;
noiseShapingR += inputSampleR - drySampleR;
}
*out1 = inputSampleL;
*out2 = inputSampleR;
*in1++;
*in2++;
*out1++;
*out2++;
}
}
| [
"jinx6568@sover.net"
] | jinx6568@sover.net |
98f4db4b4ff3a42ab99685aa60a1415c17a7c910 | 983cf97b4b0142eadfcdbd3e39590ba31f926fec | /filesystem.cpp | 529dc5eb28a6bd45f60b32f07b6c0788917992f9 | [] | no_license | gschueler/mcmap | f82d0b7881251d702ff2b88e66c0b44bf2a60f35 | caab0d21894111547ccac1bdb790254e92e07736 | refs/heads/master | 2020-12-30T17:19:33.455996 | 2010-10-20T10:52:07 | 2010-10-20T10:52:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,328 | cpp | #include "filesystem.h"
#ifdef MSVCP
#include <direct.h>
// See http://en.wikipedia.org/wiki/Stdint.h#External_links
#include <stdint.h>
#else
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <unistd.h>
#endif
#include <cstdarg>
#include <cstdlib>
#include <cstring>
#define CCEND ((char*)0)
#ifdef MSVCP
// For UTF8 conversion
#define LOWER_6_BIT(u) ((u) & 0x003f)
#define LOWER_7_BIT(u) ((u) & 0x007f)
#define BIT7(a) ((a) & 0x80)
#define BIT6(a) ((a) & 0x40)
#define BIT5(a) ((a) & 0x20)
#define BIT54(a) ((a) & 0x30)
#define BIT543(a) ((a) & 0x38)
#define BIT2(a) ((a) & 0x04)
#define BIT1(a) ((a) & 0x02)
#define BIT0(a) ((a) & 0x01)
// Return: -1 = at least one nullpointer, 1 = success, 0 = outbuffer too small
static int Utf8ToWideChar(char *pUTF8, size_t cchSrc, wchar_t *pWCHAR, size_t cchDest, bool *isvalid)
{
if (!pUTF8 || !pWCHAR) {
return -1; // Valid pointers?
}
int nTB = 0; // Number of bytes left for current char
wchar_t *pDestEnd = pWCHAR + cchDest;
char *pSrcEnd = pUTF8 + cchSrc;
char UTF8;
if (isvalid != NULL) {
*isvalid = true;
}
while ((pUTF8 < pSrcEnd) && (pWCHAR < pDestEnd)) {
if (BIT7(*pUTF8) == 0) { // normal ASCII
if (nTB) { // last mulibyte char not complete, insert '?'
nTB = 0;
*pWCHAR++ = 63;
if (isvalid != NULL) {
*isvalid = false;
}
} else { // just convert
*pWCHAR++ = (wchar_t)*pUTF8++;
}
} else if (BIT6(*pUTF8) == 0) { // utf8 sequence byte (not first)
if (nTB != 0) {
*pWCHAR <<= 6;
*pWCHAR |= LOWER_6_BIT(*pUTF8);
if (--nTB == 0) {
++pWCHAR;
}
} else { // No more trailing bytes expected, insert '?'
*pWCHAR++ = 63;
if (isvalid != NULL) {
*isvalid = false;
}
}
++pUTF8;
} else { // No ASCII and no trailing byte
if (nTB) { // but last char was multibyte and not complete yet, insert '?'
nTB = 0;
*pWCHAR++ = 63;
if (isvalid != NULL) {
*isvalid = false;
}
} else { // OK, check how many bytes
UTF8 = *pUTF8;
while (BIT7(UTF8) != 0) { // count number of bytes for this char
UTF8 <<= 1;
nTB++;
}
if (nTB > 4) { // too long, utf8 specs allow only up to 4 bytes per char
nTB = 0;
*pWCHAR++ = 63; // time for a '?'
if (isvalid != NULL) {
*isvalid = false;
}
} else { // just shift bits back and assign
*pWCHAR = UTF8 >> nTB--;
}
}
++pUTF8;
}
}
if (nTB != 0 && isvalid != NULL) {
*isvalid = false;
}
if (pWCHAR < pDestEnd) {
*pWCHAR = 0;
return 1;
}
*(pWCHAR-1) = 0;
return 0;
}
// Return: -1 = at least one nullpointer, 1 = success, 0 = outbuffer too small
template <class T>
int WideCharToUtf8(T pWCHAR, size_t cchSrc, uint8_t *pUTF8, size_t cchDest)
{
if (!pUTF8 || !pWCHAR) {
return -1; // Valid pointers?
}
uint8_t *pDestEnd = pUTF8 + cchDest;
T pSrcEnd = pWCHAR + cchSrc;
uint8_t UTF8[4];
while ((pWCHAR < pSrcEnd) && (pUTF8 < pDestEnd)) {
if (LOWER_7_BIT(*pWCHAR) == *pWCHAR) { // normal ASCII
*pUTF8++ = (uint8_t)*pWCHAR++;
} else { // utf8 encode!
int i;
for (i = 0; i < 4; ++i) {
UTF8[i] = LOWER_6_BIT(*pWCHAR) | 0x80;
*pWCHAR >>= 6;
if (*pWCHAR == 0) {
break;
}
}
bool exp = false;
if (i == 1 && BIT5(UTF8[1])) {
exp = true;
} else if (i == 2 && BIT54(UTF8[2])) {
exp = true;
} else if (i == 3 && BIT543(UTF8[3])) {
exp = true;
}
if (exp) {
++i;
UTF8[i] = (0xff) << (7 - i);
} else if (i == 1) {
UTF8[1] |= 0xc0;
} else if (i == 2) {
UTF8[2] |= 0xe0;
} else if (i == 3) {
UTF8[3] |= 0xf0;
}
do {
*pUTF8++ = UTF8[i];
if (pUTF8 >= pDestEnd) {
*(pUTF8-1) = '\0';
return 0;
}
} while (i-- > 0);
++pWCHAR;
}
}
if (pUTF8 >= pDestEnd) {
*(pUTF8-1) = '\0';
return 0;
}
*pUTF8 = 0;
return 1;
}
#endif
static size_t concat(char *buffer, const size_t len, char *source, ...)
{
if (len <= 0) {
return 0;
}
va_list parg;
size_t count = 0;
va_start(parg, source);
if (source != CCEND) do {
while (*source != 0) {
*buffer++ = *source++;
if (++count >= len) {
*(buffer-1) = 0;
va_end(parg); /* End variable argument process */
return count;
}
}
} while((source = va_arg(parg, char*)) != CCEND);
va_end(parg); /* End variable argument process */
*buffer = 0;
return count;
}
namespace Dir
{
DIRHANDLE open(char* path, myFile &file)
{
if (path == NULL) {
return NULL;
}
#ifdef MSVCP
char buffer[1000];
wchar_t wbuffer[1000];
_WIN32_FIND_DATAW ffd;
concat(buffer, 1000, path, "/*", CCEND);
bool b;
Utf8ToWideChar(buffer, strlen(buffer), wbuffer, 1000, &b);
HANDLE h = FindFirstFileW(wbuffer, &ffd);
if (h == INVALID_HANDLE_VALUE) {
return NULL;
}
WideCharToUtf8(ffd.cFileName, wcslen(ffd.cFileName), (uint8_t*)file.name, sizeof(file.name));
file.isdir = ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY);
file.size = ffd.nFileSizeLow;
#else
DIR* h = opendir(path);
if (h == NULL) {
return NULL;
}
dirent *dirp = readdir(h);
char buffer[1000];
concat(buffer, 1000, path, "/", dirp->d_name, CCEND);
struct stat stDirInfo;
if (stat(buffer, &stDirInfo) < 0) {
closedir(h);
return NULL;
}
strncpy(file.name, dirp->d_name, sizeof(file.name));
file.isdir = S_ISDIR(stDirInfo.st_mode);
file.size = stDirInfo.st_size;
#endif
return h;
}
bool next(DIRHANDLE handle, char* path, myFile &file)
{
#ifdef MSVCP
_WIN32_FIND_DATAW ffd;
bool ret = FindNextFileW(handle, &ffd) == TRUE;
if (!ret) {
return false;
}
WideCharToUtf8(ffd.cFileName, wcslen(ffd.cFileName), (uint8_t*)file.name, sizeof(file.name));
file.isdir = ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY);
file.size = ffd.nFileSizeLow;
#else
dirent *dirp = readdir(handle);
if (dirp == NULL) {
return false;
}
char buffer[1000];
concat(buffer, 1000, path, "/", dirp->d_name, CCEND);
struct stat stDirInfo;
if (stat(buffer, &stDirInfo) < 0) {
return false;
}
strncpy(file.name, dirp->d_name, sizeof(file.name));
file.isdir = S_ISDIR(stDirInfo.st_mode);
file.size = stDirInfo.st_size;
#endif
return true;
}
void close(DIRHANDLE handle)
{
#ifdef MSVCP
FindClose(handle);
#else
closedir(handle);
#endif
}
}
| [
"spam@aol.com"
] | spam@aol.com |
06a39cab64afdba9214f36e027eeae3605e911f3 | 3a484e659d6e621e518ef12b898bcd8d1ba88bc3 | /BitBuffer.cpp | ee0b39cef48eaeb4499ab56d0bb3f44379efa74b | [] | no_license | jyeon2yu/Forensic_Watermarking_Program1 | ff64297257a0a0788593061e78063658b88695f4 | fe64aa088254202ea65770881cd088612756a8b5 | refs/heads/master | 2021-12-13T16:59:21.945357 | 2021-11-12T09:08:35 | 2021-11-12T09:08:35 | 188,376,224 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 418 | cpp | #include "stdafx.h"
#include <stdexcept>
#include "BitBuffer.hpp"
namespace qrcodegen {
BitBuffer::BitBuffer()
: std::vector<bool>() {}
void BitBuffer::appendBits(std::uint32_t val, int len)
{
if (len < 0 || len > 31 || val >> len != 0)
throw std::domain_error("Value out of range");
for (int i = len - 1; i >= 0; i--) // Append bit by bit
{
this->push_back(((val >> i) & 1) != 0);
}
}
}
| [
"jyeon2yu@gmail.com"
] | jyeon2yu@gmail.com |
ff63c3bf1b21a16a9960d38399c31d9204e04840 | a1fbf16243026331187b6df903ed4f69e5e8c110 | /cs/engine/xrGame/steering_behaviour_base.h | b8621a3db1449253aa9f2397e6f0bece924db9ee | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | OpenXRay/xray-15 | ca0031cf1893616e0c9795c670d5d9f57ca9beff | 1390dfb08ed20997d7e8c95147ea8e8cb71f5e86 | refs/heads/xd_dev | 2023-07-17T23:42:14.693841 | 2021-09-01T23:25:34 | 2021-09-01T23:25:34 | 23,224,089 | 64 | 23 | NOASSERTION | 2019-04-03T17:50:18 | 2014-08-22T12:09:41 | C++ | UTF-8 | C++ | false | false | 911 | h | ////////////////////////////////////////////////////////////////////////////
// Module : steering_behaviour_base.h
// Created : 07.11.2007
// Modified : 07.11.2007
// Author : Dmitriy Iassenev
// Description : steering behaviour base class
////////////////////////////////////////////////////////////////////////////
#ifndef STEERING_BEHAVIOUR_BASE_H_INCLUDED
#define STEERING_BEHAVIOUR_BASE_H_INCLUDED
#include <boost/noncopyable.hpp>
class CAI_Rat;
namespace steering_behaviour {
class base : private boost::noncopyable {
public:
base (CAI_Rat const *object);
virtual ~base () {}
virtual Fvector direction () = 0;
public:
IC void enabled (bool const &value);
IC bool const &enabled () const;
private:
CAI_Rat const *m_object;
bool m_enabled;
};
} // namespace steering_behaviour
#include "steering_behaviour_base_inline.h"
#endif // STEERING_BEHAVIOUR_BASE_H_INCLUDED | [
"paul-kv@yandex.ru"
] | paul-kv@yandex.ru |
52df1ddb3edebe4d512553ae12b1a496491a1460 | 2b79bbce9496b2c5bddcf6fa93698b77f778d9eb | /2020.10.27 確認テストその2/3.cpp | 71d6b0427b01827b5114f0e164b9d707d7c099b9 | [] | no_license | YumiNose/2020.10.27-2 | 39979d189d2b14f9655270b969688763caf7c1fb | 0cec03e95f31f402680ccf5ca29d87b9eadd60e8 | refs/heads/master | 2023-01-04T16:55:33.541527 | 2020-10-27T03:12:08 | 2020-10-27T03:12:08 | 307,571,352 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 288 | cpp | /*
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void InitRand()
{
srand((unsigned int)time(NULL));
}
int Random()
{
return rand() % 10 + 1;
}
int main()
{
InitRand();
for (int i = 0; i < 10; ++i)
{
cout << Random() << ' ';
}
cout << endl;
}
*/ | [
"yumi.nose28@gmail.com"
] | yumi.nose28@gmail.com |
8c57d57b476ddc87f31380d8c42688a15a7d7b58 | 73b80a1074ad8b9999e4dd78c86a6baad32bfce5 | /Core/3rdParty/2DPieGraph.cpp | 8e362c35cea5e8a06c9321b1449da08235b153f2 | [] | no_license | abstractspoon/ToDoList_Dev | 25f463dea727b71ae30ca8de749570baa451aa13 | 29d038a7ff54150af21094f317e4f7c7d2dd118d | refs/heads/master | 2023-08-31T21:18:16.238149 | 2023-08-29T01:24:16 | 2023-08-29T01:24:16 | 66,343,401 | 87 | 26 | null | 2023-09-09T08:16:35 | 2016-08-23T07:19:50 | C++ | UTF-8 | C++ | false | false | 22,002 | cpp | // 2DPieGraph.cpp: implementation of the C2DPieGraph class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "2DPieGraph.h"
#include "mathparams.h"
#include <math.h>
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
C2DPieGraph::~C2DPieGraph()
{
ClearGraph();
// Delete graph legend font
m_LegendFont->DeleteObject();
delete m_LegendFont;
m_LegendFont = NULL;
// Free graph blend DC and bitmap
::SelectObject( m_hBlendDC, m_hOldBlendBitmap );
::DeleteDC( m_hBlendDC );
::DeleteObject( m_hBlendBitmap );
}
C2DPieGraph::C2DPieGraph(CPoint g_position, CSize g_size)
{
// Set graph position and size
m_Position = g_position;
m_Size = g_size;
// Set graph segments number
m_SegmentsNumber = 0;
m_Segments = NULL;
// Set graph legend font
m_LegendFont = new CFont();
m_LegendFont->CreateFont( int(m_Size.cy*0.075), 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_CHARACTER_PRECIS, CLIP_CHARACTER_PRECIS,
PROOF_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Arial") );
// Set default graph background color
m_GraphBkColor = RGB(255,255,2555);
// Set default graph legend background and text color
m_LegendBackgroundColor = RGB(255,255,255);
m_LegendTextColor = RGB(0,0,0);
}
void C2DPieGraph::BuildGraph(HDC hDC)
{
_2DPieGraphSegments *curr = m_Segments;
double angle;
int endX, endY;
CBrush* pBrush = NULL;
HGDIOBJ hOldBrush;
bool animFlag = false;
m_DrawPercentCompleted = 0;
// Set start angle
double startAngle = 0.0;
// Set start point
int startX = m_Position.x + m_Size.cx;
int startY = m_Position.y + m_Size.cy/2;
// Draw graph segments
while ( curr != NULL )
{
// If animation running
if ( m_Animation == TRUE )
{
// If running draw animation
if ( m_AnimationType == AT_PIE_DRAW )
{
int seg_percent = int((double(m_DrawPercentCompleted+curr->percent)/double(m_DrawTotalPercent)) * 100.0 + 0.5);
// If drawing complete graph segment
if ( m_AnimationPercent > seg_percent )
{
// Calculate completed animation percent
m_DrawPercentCompleted += curr->percent;
// Set graph segment start angle
angle = startAngle;
// Calculate graph segment start position
if ( ( ( angle >= 0 ) && ( angle <= (PI/2) ) ) || ( ( angle >= (3*PI/2) ) && ( angle <= (2*PI) ) ) )
startX = m_Position.x + int(double(m_Size.cx)/2.0 + (double(m_Size.cx)/2.0) * cos(angle) + 0.5);
else if ( ( angle >= (PI/2) ) && ( angle <= (3*PI/2) ) )
startX = m_Position.x + int(double(m_Size.cx)/2.0 + (double(m_Size.cx)/2.0) * cos(angle) + 0.5);
if ( ( angle >= 0 ) && ( angle <= (PI) ) )
startY = m_Position.y + int(double(m_Size.cy)/2.0 - (double(m_Size.cy)/2.0) * sin(angle) + 0.5);
else if ( ( angle >= (PI) ) && ( angle <= (2*PI) ) )
startY = m_Position.y + int(double(m_Size.cy)/2.0 - (double(m_Size.cy)/2.0) * sin(angle) + 0.5);
// Set graph segment end angle
angle = startAngle + (double(curr->percent)/100.0) * (2*PI);
// Calculate graph segment end position
if ( ( ( angle >= 0 ) && ( angle <= (PI/2) ) ) || ( ( angle >= (3*PI/2) ) && ( angle <= (2*PI) ) ) )
endX = m_Position.x + int(double(m_Size.cx)/2.0 + (double(m_Size.cx)/2.0) * cos(angle) + 0.5);
else if ( ( angle >= (PI/2) ) && ( angle <= (3*PI/2) ) )
endX = m_Position.x + int(double(m_Size.cx)/2.0 + (double(m_Size.cx)/2.0) * cos(angle) + 0.5);
if ( ( angle >= 0 ) && ( angle <= (PI) ) )
endY = m_Position.y + int(double(m_Size.cy)/2.0 - (double(m_Size.cy)/2.0) * sin(angle) + 0.5);
else if ( ( angle >= (PI) ) && ( angle <= (2*PI) ) )
endY = m_Position.y + int(double(m_Size.cy)/2.0 - (double(m_Size.cy)/2.0) * sin(angle) + 0.5);
// Set new animation start point
m_AnimationStartPoint = CPoint( endX, endY );
if ( ( startX != endX ) || ( startY != endY ) )
{
// Draw graph segment
pBrush = new CBrush();
pBrush->CreateSolidBrush( curr->color );
hOldBrush = ::SelectObject( hDC, pBrush->GetSafeHandle() );
::Pie( hDC, m_Position.x, m_Position.y, m_Position.x + m_Size.cx, m_Position.y + m_Size.cy,
startX, startY, endX, endY );
::SelectObject( hDC, hOldBrush );
pBrush->DeleteObject();
delete pBrush;
}
}
// If drawing part of the graph segment
else
{
// Calculate graph segment animation angle
if ( ( ( m_DrawAnimationAngle >= 0 ) && ( m_DrawAnimationAngle <= (PI/2) ) ) || ( ( m_DrawAnimationAngle >= (3*PI/2) ) && ( m_DrawAnimationAngle <= (2*PI) ) ) )
endX = m_Position.x + int(double(m_Size.cx)/2.0 + (double(m_Size.cx)/2.0) * cos(m_DrawAnimationAngle) + 0.5);
else if ( ( m_DrawAnimationAngle >= (PI/2) ) && ( m_DrawAnimationAngle <= (3*PI/2) ) )
endX = m_Position.x + int(double(m_Size.cx)/2.0 + (double(m_Size.cx)/2.0) * cos(m_DrawAnimationAngle) + 0.5);
if ( ( m_DrawAnimationAngle >= 0 ) && ( m_DrawAnimationAngle <= (PI) ) )
endY = m_Position.y + int(double(m_Size.cy)/2.0 - (double(m_Size.cy)/2.0) * sin(m_DrawAnimationAngle) + 0.5);
else if ( ( m_DrawAnimationAngle >= (PI) ) && ( m_DrawAnimationAngle <= (2*PI) ) )
endY = m_Position.y + int(double(m_Size.cy)/2.0 - (double(m_Size.cy)/2.0) * sin(m_DrawAnimationAngle) + 0.5);
if ( ( m_AnimationStartPoint.x != endX ) || ( m_AnimationStartPoint.y != endY ) )
{
// Draw graph segment
pBrush = new CBrush();
pBrush->CreateSolidBrush( curr->color );
hOldBrush = ::SelectObject( hDC, pBrush->GetSafeHandle() );
::Pie( hDC, m_Position.x, m_Position.y, m_Position.x + m_Size.cx, m_Position.y + m_Size.cy,
m_AnimationStartPoint.x, m_AnimationStartPoint.y, endX, endY );
::SelectObject( hDC, hOldBrush );
pBrush->DeleteObject();
delete pBrush;
}
// Exit animation loop
break;
}
}
// If running blend animation
if ( m_AnimationType == AT_PIE_BLEND )
{
// Check current graph segment index
if ( curr->index > m_BlendSegments )
{
// Create graph blend DC and bitmap
m_hBlendDC = ::CreateCompatibleDC( hDC );
m_hBlendBitmap = ::CreateCompatibleBitmap( hDC, m_FullSize.cx, m_FullSize.cy );
m_hOldBlendBitmap = (HBITMAP)::SelectObject( m_hBlendDC, m_hBlendBitmap );
// Create temporary DC and bitmap
HDC tempDC = ::CreateCompatibleDC( hDC );
HBITMAP tempBitmap = ::CreateCompatibleBitmap( hDC, m_FullSize.cx, m_FullSize.cy );
HBITMAP m_tempOldBitmap = (HBITMAP)::SelectObject( tempDC, tempBitmap );
// Clear graph blend and temporary DC
::BitBlt( m_hBlendDC, 0, 0, m_FullSize.cx, m_FullSize.cy, hDC, 0, 0, SRCCOPY );
::BitBlt( tempDC, 0, 0, m_FullSize.cx, m_FullSize.cy, hDC, 0, 0, SRCCOPY );
// Set graph segment end angle
angle = startAngle + (double(curr->percent)/100.0) * (2*PI);
// Calculate graph segment end position
if ( ( ( angle >= 0 ) && ( angle <= (PI/2) ) ) || ( ( angle >= (3*PI/2) ) && ( angle <= (2*PI) ) ) )
endX = m_Position.x + m_Size.cx/2 + int( (m_Size.cx/2) * cos( angle ) );
else if ( ( angle >= (PI/2) ) && ( angle <= (3*PI/2) ) )
endX = m_Position.x + m_Size.cx/2 + int( (m_Size.cx/2) * cos( angle ) );
if ( ( angle >= 0 ) && ( angle <= (PI) ) )
endY = m_Position.y + m_Size.cy/2 - int( (m_Size.cy/2) * sin( angle ) );
else if ( ( angle >= (PI) ) && ( angle <= (2*PI) ) )
endY = m_Position.y + m_Size.cy/2 - int( (m_Size.cy/2) * sin( angle ) );
// Draw graph segment
pBrush = new CBrush();
pBrush->CreateSolidBrush( curr->color );
hOldBrush = ::SelectObject( m_hBlendDC, pBrush->GetSafeHandle() );
::Pie( m_hBlendDC, m_Position.x, m_Position.y, m_Position.x + m_Size.cx, m_Position.y + m_Size.cy,
m_AnimationStartPoint.x, m_AnimationStartPoint.y, endX, endY );
::SelectObject( m_hBlendDC, hOldBrush );
pBrush->DeleteObject();
delete pBrush;
// Do alpha blending on temporary DC
BLENDFUNCTION bf;
bf.BlendOp = AC_SRC_OVER;
bf.BlendFlags = 0;
bf.AlphaFormat = 0;
bf.SourceConstantAlpha = BYTE((double(m_AnimationPercent)/100.0)*255);
::AlphaBlend( tempDC, m_Position.x, m_Position.y, m_Size.cx, m_Size.cy, m_hBlendDC, m_Position.x, m_Position.y, m_Size.cx, m_Size.cy, bf );
// Do transparent bliting on destination DC
::TransparentBlt( hDC, m_Position.x, m_Position.y, m_Size.cx, m_Size.cy, tempDC, m_Position.x, m_Position.y, m_Size.cx, m_Size.cy, ::GetPixel(tempDC,m_Position.x,m_Position.y) );
// Draw finished graph segments
double angle_total = 0.0;
_2DPieGraphSegments *tmp_seg = m_Segments;
while ( tmp_seg->index-1 < m_BlendSegments )
{
// Set graph segment start angle
angle = angle_total;
// Calculate graph segment start position
if ( ( ( angle >= 0 ) && ( angle <= (PI/2) ) ) || ( ( angle >= (3*PI/2) ) && ( angle <= (2*PI) ) ) )
startX = m_Position.x + int(double(m_Size.cx)/2.0 + (double(m_Size.cx)/2.0) * cos(angle) + 0.5);
else if ( ( angle >= (PI/2) ) && ( angle <= (3*PI/2) ) )
startX = m_Position.x + int(double(m_Size.cx)/2.0 + (double(m_Size.cx)/2.0) * cos(angle) + 0.5);
if ( ( angle >= 0 ) && ( angle <= (PI) ) )
startY = m_Position.y + int(double(m_Size.cy)/2.0 - (double(m_Size.cy)/2.0) * sin(angle) + 0.5);
else if ( ( angle >= (PI) ) && ( angle <= (2*PI) ) )
startY = m_Position.y + int(double(m_Size.cy)/2.0 - (double(m_Size.cy)/2.0) * sin(angle) + 0.5);
// Set graph segment end angle
angle = angle_total + (double(tmp_seg->percent)/100.0) * (2*PI);
// Calculate graph segment end position
if ( ( ( angle >= 0 ) && ( angle <= (PI/2) ) ) || ( ( angle >= (3*PI/2) ) && ( angle <= (2*PI) ) ) )
endX = m_Position.x + int(double(m_Size.cx)/2.0 + (double(m_Size.cx)/2.0) * cos(angle) + 0.5);
else if ( ( angle >= (PI/2) ) && ( angle <= (3*PI/2) ) )
endX = m_Position.x + int(double(m_Size.cx)/2.0 + (double(m_Size.cx)/2.0) * cos(angle) + 0.5);
if ( ( angle >= 0 ) && ( angle <= (PI) ) )
endY = m_Position.y + int(double(m_Size.cy)/2.0 - (double(m_Size.cy)/2.0) * sin(angle) + 0.5);
else if ( ( angle >= (PI) ) && ( angle <= (2*PI) ) )
endY = m_Position.y + int(double(m_Size.cy)/2.0 - (double(m_Size.cy)/2.0) * sin(angle) + 0.5);
// Draw graph segment
pBrush = new CBrush();
pBrush->CreateSolidBrush( tmp_seg->color );
hOldBrush = ::SelectObject( hDC, pBrush->GetSafeHandle() );
::Pie( hDC, m_Position.x, m_Position.y, m_Position.x + m_Size.cx, m_Position.y + m_Size.cy,
startX, startY, endX, endY );
::SelectObject( hDC, hOldBrush );
pBrush->DeleteObject();
delete pBrush;
// Calculate start angle
angle_total += (double(tmp_seg->percent)/100.0) * (2*PI);
// Get next segment
tmp_seg = tmp_seg->next;
}
// Delete graph blend DC and bitmap
::SelectObject( m_hBlendDC, m_hOldBlendBitmap );
::DeleteDC( m_hBlendDC );
::DeleteObject( m_hBlendBitmap );
// Delete temporary DC and bitmap
::SelectObject( tempDC, m_tempOldBitmap );
::DeleteDC( tempDC );
::DeleteObject( tempBitmap );
// Set next graph segment start point
if ( m_AnimationPercent >= 100 )
m_AnimationStartPoint = CPoint( endX, endY );
// Exit animation loop
break;
}
}
}
// If no animation running
else
{
// Set graph segment end angle
angle = startAngle + (double(curr->percent)/100.0) * (2*PI);
// Calculate graph segment end position
if ( ( ( angle >= 0 ) && ( angle <= (PI/2) ) ) || ( ( angle >= (3*PI/2) ) && ( angle <= (2*PI) ) ) )
endX = m_Position.x + m_Size.cx/2 + int( (m_Size.cx/2) * cos( angle ) );
else if ( ( angle >= (PI/2) ) && ( angle <= (3*PI/2) ) )
endX = m_Position.x + m_Size.cx/2 + int( (m_Size.cx/2) * cos( angle ) );
if ( ( angle >= 0 ) && ( angle <= (PI) ) )
endY = m_Position.y + m_Size.cy/2 - int( (m_Size.cy/2) * sin( angle ) );
else if ( ( angle >= (PI) ) && ( angle <= (2*PI) ) )
endY = m_Position.y + m_Size.cy/2 - int( (m_Size.cy/2) * sin( angle ) );
// Draw graph segment
pBrush = new CBrush();
pBrush->CreateSolidBrush( curr->color );
hOldBrush = ::SelectObject( hDC, pBrush->GetSafeHandle() );
::Pie( hDC, m_Position.x, m_Position.y, m_Position.x + m_Size.cx, m_Position.y + m_Size.cy,
startX, startY, endX, endY );
::SelectObject( hDC, hOldBrush );
pBrush->DeleteObject();
delete pBrush;
// Set next graph segment start point
startX = endX;
startY = endY;
}
// Calculate start angle
startAngle += (double(curr->percent)/100.0) * (2*PI);
// Next graph segment
curr = curr->next;
}
}
void C2DPieGraph::AddSegment(int s_percent, COLORREF s_color, CString s_text)
{
// Get total percent
int percentTotal = 0;
_2DPieGraphSegments* cs = m_Segments;
while ( cs != NULL )
{
percentTotal += cs->percent;
cs = cs->next;
}
// Set total percent
m_DrawTotalPercent = percentTotal;
// Check percent bounds
if ( s_percent < 0 )
s_percent = 0;
else if ( s_percent > 100 )
s_percent = 100;
else if ( ( percentTotal + s_percent ) > 100 )
s_percent = 100 - percentTotal;
// Check percent left
if ( s_percent > 0 )
{
m_DrawTotalPercent += s_percent;
// Increment segments number
m_SegmentsNumber++;
// Create new graph segment
_2DPieGraphSegments* newSegment = new _2DPieGraphSegments;
newSegment->percent = s_percent;
newSegment->color = s_color;
newSegment->index = m_SegmentsNumber;
newSegment->text = s_text;
newSegment->next = NULL;
// Add new segment to the graph
_2DPieGraphSegments* curr = m_Segments;
if ( curr == NULL )
m_Segments = newSegment;
else
{
while ( curr->next != NULL )
curr = curr->next;
curr->next = newSegment;
}
}
}
void C2DPieGraph::DeleteSegment(int s_index)
{
// Check index bounds
if ( ( s_index < 1 ) || ( s_index > m_SegmentsNumber ) )
AfxMessageBox( _T("Index is out of bounds..."), MB_OK, NULL );
else
{
_2DPieGraphSegments *curr, *prev;
curr = m_Segments;
prev = NULL;
// Delete first graph segment
if ( curr->index == s_index )
{
if ( m_SegmentsNumber == 1 )
{
// Set segment parameters
m_Segments = NULL;
m_SegmentsNumber = 0;
}
else
{
// Decrement segments number
m_SegmentsNumber--;
}
m_Segments = curr->next;
delete curr;
}
// Delete other graph segment
else
{
while ( curr->index < s_index )
{
prev = curr;
curr = curr->next;
}
prev->next = curr->next;
delete curr;
// Decrement segments number
m_SegmentsNumber--;
}
// Get total percent
int percentTotal = 0;
_2DPieGraphSegments* cs = m_Segments;
int ind = 1;
while ( cs != NULL )
{
// Reindex graph segments
cs->index = ind;
percentTotal += cs->percent;
cs = cs->next;
ind++;
}
// Set total percent
m_DrawTotalPercent = percentTotal;
}
}
void C2DPieGraph::ClearGraph()
{
_2DPieGraphSegments *curr, *prev;
// Delete all graph segments
curr = m_Segments;
while ( curr != NULL )
{
prev = curr;
curr = curr->next;
delete prev;
}
// Set graph segment parameters
m_Segments = NULL;
m_SegmentsNumber = 0;
}
void C2DPieGraph::SetGraphAnimation(BOOL g_animation, int a_type)
{
// Set graph animation parameters
m_Animation = g_animation;
m_AnimationType = a_type;
m_AnimationPercent = 0;
m_AnimationStartPoint = CPoint( m_Position.x + m_Size.cx, m_Position.y + m_Size.cy/2 );
// Check graph animation flag
if ( m_Animation == TRUE )
{
// If setting draw graph animation type
if ( m_AnimationType == AT_PIE_DRAW )
{
m_DrawAnimationAngle = 0.0;
m_DrawPercentCompleted = 0;
}
// If setting blend graph animation type
else if ( m_AnimationType == AT_PIE_BLEND )
{
// Set total blended segments
m_BlendSegments = 0;
}
}
}
BOOL C2DPieGraph::GetGraphAnimation()
{
return m_Animation;
}
int C2DPieGraph::GetGraphAnimationPercent()
{
return m_AnimationPercent;
}
void C2DPieGraph::BuildGraphLegend(HDC hDC)
{
_2DPieGraphSegments *curr = m_Segments;
// Select legend font
HGDIOBJ hOldFont = ::SelectObject( hDC, m_LegendFont->GetSafeHandle() );
// Get text size
CSize ts;
::GetTextExtentPoint32( hDC, _T("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 26, &ts );
int offset = (m_Size.cy - int(m_SegmentsNumber*ts.cy))/2;
CPoint start = CPoint( m_Position.x + int(m_Size.cx*1.15), m_Position.y + int(m_Size.cy*0.014) + offset );
CSize sz;
CString str = "";
CRect rect;
CBrush* rBrush = NULL;
// Draw graph legend
CBrush bgBrush( m_LegendBackgroundColor );
HBRUSH hOldBrush = (HBRUSH)::SelectObject( hDC, bgBrush.GetSafeHandle() );
::Rectangle( hDC, m_Position.x + int(m_Size.cx*1.1), m_Position.y + offset, m_Position.x + int(m_Size.cx*1.75), m_Position.y + int((m_SegmentsNumber+0.5)*ts.cy + offset) );
::SelectObject( hDC, hOldBrush );
bgBrush.DeleteObject();
COLORREF oldTextColor = ::SetTextColor( hDC, m_LegendTextColor );
while ( curr != NULL )
{
// Draw segment color field
rect = CRect( start.x, start.y + int(m_Size.cy*0.05)/2, start.x + int(m_Size.cx*0.1), start.y + int(m_Size.cy*0.075) );
rBrush = new CBrush();
rBrush->CreateSolidBrush( curr->color );
::FillRect( hDC, rect, (HBRUSH)rBrush->GetSafeHandle() );
rBrush->DeleteObject();
delete rBrush;
// Draw segment text
str.Format( _T("(%d%s) %s"), curr->percent, _T("%"), curr->text );
::SetBkMode( hDC, TRANSPARENT );
::TextOut( hDC, start.x + rect.Width() + int(m_Size.cx*0.01), start.y, str, str.GetLength() );
::SetBkMode( hDC, OPAQUE );
// Recalculate next text position
::GetTextExtentPoint32( hDC, curr->text, curr->text.GetLength(), &sz );
start.y += sz.cy;
// Get next graph segment
curr = curr->next;
}
::SetTextColor( hDC, oldTextColor );
// Select old font
::SelectObject( hDC, hOldFont );
}
void C2DPieGraph::UpdateAnimation()
{
if ( m_Animation == TRUE )
{
// If running draw animation
if ( m_AnimationType == AT_PIE_DRAW )
{
// Set total angle
double totalAngle = (double(m_DrawTotalPercent)/100.0) * (2*PI);
// Check completed animation
if ( ( m_DrawPercentCompleted > m_DrawTotalPercent ) || ( m_AnimationPercent > 100 ) )
{
m_DrawPercentCompleted = 0;
m_AnimationPercent = 0;
m_AnimationStartPoint = CPoint( m_Position.x + m_Size.cx, m_Position.y + m_Size.cy/2 );
}
// Increment animation percent
m_AnimationPercent++;
// Set animation angle
m_DrawAnimationAngle = totalAngle * double(m_AnimationPercent)/100.0;
}
// If running blend animation
else if ( m_AnimationType == AT_PIE_BLEND )
{
// Check completed animation percent
if ( m_AnimationPercent >= 100 )
{
m_AnimationPercent = 0;
// Increment completed graph segments
m_BlendSegments++;
// Check completed graph segments
if ( m_BlendSegments >= m_SegmentsNumber )
{
m_BlendSegments = 0;
m_AnimationStartPoint = CPoint( m_Position.x + m_Size.cx, m_Position.y + m_Size.cy/2 );
}
}
// Increment animation percent
m_AnimationPercent += 2;
}
}
}
void C2DPieGraph::SetGraphBkColor(COLORREF g_bkColor)
{
// Set graph background color
m_GraphBkColor = g_bkColor;
}
void C2DPieGraph::UpdateSegment(int s_index, int s_percent, COLORREF s_color, CString s_text)
{
// Check index bounds
if ( ( s_index < 1 ) || ( s_index > m_SegmentsNumber ) )
AfxMessageBox( _T("Index is out of bounds..."), MB_OK, NULL );
// Check percent
else if ( s_percent <= 0 )
AfxMessageBox( _T("Percent is not valid..."), MB_OK, NULL );
else
{
_2DPieGraphSegments *curr = m_Segments;
// Find graph segment
while ( curr->index != s_index )
curr = curr->next;
// Update segment data
curr->percent = s_percent;
curr->color = s_color;
curr->text = s_text;
// Get total percent
int percentTotal = 0;
_2DPieGraphSegments* cs = m_Segments;
int ind = 1;
while ( cs != NULL )
{
percentTotal += cs->percent;
cs = cs->next;
ind++;
}
// Set total percent
m_DrawTotalPercent = percentTotal;
// Update graph animation parameters
m_AnimationPercent = 0;
m_AnimationStartPoint = CPoint( m_Position.x + m_Size.cx, m_Position.y + m_Size.cy/2 );
// Check graph animation flag
if ( m_Animation == TRUE )
{
// If setting draw graph animation type
if ( m_AnimationType == AT_PIE_DRAW )
{
m_DrawAnimationAngle = 0.0;
m_DrawPercentCompleted = 0;
}
// If setting blend graph animation type
else if ( m_AnimationType == AT_PIE_BLEND )
{
// Set total blended segments
m_BlendSegments = 0;
}
}
}
}
void C2DPieGraph::SetGraphSize(CSize g_size)
{
// Set new graph size
m_Size = g_size;
// Set new graph legend font size
m_LegendFont->DeleteObject();
delete m_LegendFont;
m_LegendFont = new CFont();
m_LegendFont->CreateFont( int(m_Size.cy*0.08), int(m_Size.cx*0.035), 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_CHARACTER_PRECIS, CLIP_CHARACTER_PRECIS,
PROOF_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Times New Roman") );
}
void C2DPieGraph::SetGraphPosition(CPoint g_position)
{
// Set new graph position
m_Position = g_position;
}
void C2DPieGraph::SetFullSize(CSize full_size)
{
// Set full size
m_FullSize = full_size;
}
void C2DPieGraph::SetLegendBackgroundColor(COLORREF l_bgcolor)
{
// Set legend background color
m_LegendBackgroundColor = l_bgcolor;
}
COLORREF C2DPieGraph::GetLegendBackgroundColor()
{
return m_LegendBackgroundColor;
}
void C2DPieGraph::SetLegendTextColor(COLORREF t_color)
{
// Set legend text color
m_LegendTextColor = t_color;
}
COLORREF C2DPieGraph::GetLegendTextColor()
{
return m_LegendTextColor;
}
| [
"daniel.godson@gmail.com"
] | daniel.godson@gmail.com |
0b8d6c1d1e21e4b9cfd3040652dfc69dcbbc8d7c | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/MuonSpectrometer/MuonCnv/MuonEventTPCnv/src/MuonRIO_OnTrack/CscClusterOnTrackCnv_p2.cxx | 25b4e6853bfe1154f1aedded9c52d5188f41e0c3 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,097 | cxx | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
//-----------------------------------------------------------------------------
//
// file: CscClusterOnTrackCnv_p2.cxx
//
//-----------------------------------------------------------------------------
#include "MuonRIO_OnTrack/CscClusterOnTrack.h"
#include "MuonEventTPCnv/MuonRIO_OnTrack/CscClusterOnTrackCnv_p2.h"
#include "TrkEventTPCnv/helpers/EigenHelpers.h"
void CscClusterOnTrackCnv_p2::
persToTrans( const Muon::CscClusterOnTrack_p2 *persObj,
Muon::CscClusterOnTrack *transObj, MsgStream &log )
{
ElementLinkToIDC_CSC_Container rio;
m_elCnv.persToTrans(&persObj->m_prdLink,&rio,log);
Trk::LocalParameters localParams;
fillTransFromPStore( &m_localParCnv, persObj->m_localParams, &localParams, log );
Trk::ErrorMatrix dummy;
Amg::MatrixX localCovariance;
fillTransFromPStore( &m_errorMxCnv, persObj->m_localErrMat, &dummy, log );
EigenHelpers::vectorToEigenMatrix(dummy.values, localCovariance, "CscClusterOnTrackCnv_p2");
*transObj = Muon::CscClusterOnTrack (rio,
localParams,
localCovariance,
Identifier(persObj->m_id),
nullptr, // detEL
persObj->m_positionAlongStrip,
static_cast<const Muon::CscClusterStatus>((persObj->m_status)&0xFF), // First 8 bits reserved for ClusterStatus.
static_cast<const Muon::CscTimeStatus>((persObj->m_status)>>8),
persObj->m_time);
m_eventCnvTool->recreateRIO_OnTrack(const_cast<Muon::CscClusterOnTrack *>(transObj));
if (transObj->detectorElement()==0)
log << MSG::WARNING<<"Unable to reset DetEl for this RIO_OnTrack, "
<< "probably because of a problem with the Identifier/IdentifierHash : ("
<< transObj->identify()<<"/"<<transObj->idDE()<<endreq;
}
void CscClusterOnTrackCnv_p2::
transToPers( const Muon::CscClusterOnTrack *transObj,
Muon::CscClusterOnTrack_p2 *persObj, MsgStream &log )
{
// Prepare ELs
m_eventCnvTool->prepareRIO_OnTrack(const_cast<Muon::CscClusterOnTrack *>(transObj));
m_elCnv.transToPers(&transObj->prepRawDataLink(),&persObj->m_prdLink,log);
persObj->m_id = transObj->identify().get_identifier32().get_compact();
persObj->m_localParams = toPersistent( &m_localParCnv, &transObj->localParameters(), log );
// persObj->m_localErrMat = toPersistent( &m_errorMxCnv, &transObj->m_localErrMat, log );
Trk::ErrorMatrix pMat;
EigenHelpers::eigenMatrixToVector(pMat.values, transObj->localCovariance(), "CscClusterOnTrackCnv_p2");
persObj->m_localErrMat = toPersistent( &m_errorMxCnv, &pMat, log );
persObj->m_status = (transObj->timeStatus()<<8); // First 8 bits reserved for ClusterStatus.
persObj->m_status += transObj->status();
persObj->m_positionAlongStrip = transObj->positionAlongStrip();
persObj->m_time = transObj->time();
}
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
b764c426771a73ad17a9836eff979fb62461c13b | 6b0a4f401b8bf69ddd757809240ee828e2277e69 | /DummyClientFramework/DummyClientFramework/Custom.hh | 61d14520254eab043d78f1bea39c93214439d639 | [
"MIT"
] | permissive | GameForPeople/dummy-client-framework | 84da1572c6db2646fa8e01ff60df526e039fbe03 | 46f75da426a68a88fa3e97f5c2f84bb5f1ad000a | refs/heads/master | 2020-06-09T04:45:53.740560 | 2019-11-27T10:38:49 | 2019-11-27T10:38:49 | 193,372,933 | 2 | 1 | null | null | null | null | UHC | C++ | false | false | 8,361 | hh | #pragma once
#pragma region [더미 클라이언트 정의]
#define DUMMY_CLIENT_TEST_MODE 0 // 0 이면 디폴트 테스트 모드, 1이면 핫스팟 테스트 모드
#define DUMMY_CLIENT_SIGN_MODE 0 // 0 이면 최초 로그인 패킷, 1이면 계정 생성 요청 패킷
#if DUMMY_CLIENT_TEST_MODE == 0
#define DEFAULT_TEST_MODE
#else
#define HOTSPOT_TEST_MODE // 핫 스팟 테스트 모드.
#endif
#if DUMMY_CLIENT_SIGN_MODE == 0
#define LOGIN_MODE // 계정 로그인 모드
#else
#define SIGNUP_MODE // 계정 생성 모드
#endif
#define __ON 1
#define __OFF 0
#define USE_CONTROLLED_CLIENT __ON
#define USE_TIMER_MANAGER __ON
#define USE_LOG_MANAGER __OFF // 현재 정상적으로 동작하지 않습니다.
#define USE_PERFORMANCE_MANAGER __OFF // 현재 동작하지 않습니다.
#define USE_RENDERMODEL_MANAGER __OFF // 현재 동작하지 않습니다.
#pragma endregion
namespace NETWORK
{
const static std::string SERVER_IP = "127.0.0.1";
constexpr static unsigned short SERVER_PORT = 9000;
constexpr static int MAX_RECV_SIZE = 1000; // 한번에 RECV가 가능한 최대 크기입니다.
constexpr static int MAX_SEND_SIZE = 127; // 한번에 SEND가 가능한 최대 크기입니다. Send하는 프로토콜 - 패킷 중, sizeof(char)보다 큰 사이즈의 패킷이 존재할 경우 해당 프레임워크를 사용할 수 없습니다.
constexpr static int MAX_PACKET_SIZE = 127; // Packet의 최대 크기입니다. sizeof(char)보다 큰 사이즈의 패킷이 존재할 경우 해당 프레임워크를 사용할 수 없습니다.
}
namespace WINDOW
{
constexpr static int WINDOW_WIDTH = 800; // 윈도우의 X Size 변경 시, 수정해주세요.
constexpr static int WINDOW_HEIGHT = 800; // 윈도우의 Y Size 변경 시, 수정해주세요.
constexpr static int MAIN_TIMER_INDEX = 1;
constexpr static int MAIN_TIMER_FRAME = 1000; // WinAPI의 프레임을 변경 시, 수정해주세요. ex) 17(60FPS), 33(30FPS)
}
namespace FRAMEWORK
{
constexpr static int MAX_CLIENT = 1000; // 테스트하려는 클라이언트 수를 변경하고자 할 때, 수정해주세요.
constexpr static int WORKER_THREAD_COUNT = 3; // 더미 클라이언트에 사용할 워커쓰레드 개수를 설정해주세요.
constexpr static int CONNECTED_CLIENT_COUNT_IN_ONE_FRAME = 10; // Max Client까지 커넥트 하는 중일 떄, 한 틱에 커넥트 시도할 클라이언트 수.
constexpr static int MAX_COUNT_MEMORY_UNIT_OF_SEND_POOL = 1000000; // Send Memory Pool의 최초 할당 메모리 유닛 개수입니다.
constexpr static int ALLOCATE_COUNT_MEMORY_UNIT_OF_SEND_POOL = 100000; // Send Memory Pool의 try_pop가 실패하는 경우(메모리풀이 빔), 메모리풀에 메모리를 추가할당하는 사이즈입니다.
constexpr static int PRE_ALLOCATION_TIMER_UNIT_COUNT = 100000; // Timer Unit Pool의 사이즈!
constexpr static int MAX_ID_LENGTH = 10;
}
namespace GAME
{
constexpr static int ZONE_MIN_X = 0; // 테스트 하는 서버 Zone의 X 최저값 좌표입니다.
constexpr static int ZONE_MIN_Y = 0; // 테스트 하는 서버 Zone의 Y 최저값 좌표입니다.
constexpr static int ZONE_MAX_X = 300; // 테스트 하는 서버 Zone의 X 최대값 좌표입니다.
constexpr static int ZONE_MAX_Y = 300; // 테스트 하는 서버 Zone의 Y 최대값 좌표입니다.
constexpr static int ZONE_X_SIZE = ZONE_MAX_X - ZONE_MIN_X; //
constexpr static int ZONE_Y_SIZE = ZONE_MAX_Y - ZONE_MIN_Y; //
constexpr static int ACTOR_X_SIZE = 1500 / ZONE_X_SIZE;
constexpr static int ACTOR_Y_SIZE = 1500 / ZONE_Y_SIZE;
#if USE_CONTROLLED_CLIENT == __ON
constexpr static int BROADCAST_X_SIZE = 10; // USE_CONTROLLED_CLIENT의 시야 X입니다.
constexpr static int BROADCAST_Y_SIZE = 10; // USE_CONTROLLED_CLIENT의 시야 Y입니다.
constexpr static int BROADCAST_X_RENDER_SIZE = ACTOR_X_SIZE * BROADCAST_X_SIZE / 2;
constexpr static int BROADCAST_Y_RENDER_SIZE = ACTOR_Y_SIZE * BROADCAST_Y_SIZE / 2;
#endif
}
namespace USING_DEFINE
{
using _PosType = unsigned short;
using _ClientIndexType = unsigned int;
using _PacketSizeType = unsigned char;
using _PacketType = unsigned char;
using _DirectionType = unsigned char;
using _TimeType = unsigned long long;
using _TimeDataType = long long;
using _IDType = wchar_t;
}using namespace USING_DEFINE;
enum class TIME : _TimeType
{
SECOND = 1000
, MINUTE = 60000
, SKILL = 1000
, ITEM = 2500
};
enum class TIMER_TYPE : unsigned char
{
NONE_TYPE // 기본생성자.
, AWAKE_TYPE // 로그인 true 패킷 전달시 처리하게되는 인자.
, ATTACK_TYPE // 기본 공격
, SKILL_TYPE // 스킬 타입
, USE_ITEM_TYPE // 아이템 타입
, MOVE_TYPE
};
namespace MEMORY
{
#pragma region [FIXED]
struct BaseMemoryUnit
{
BaseMemoryUnit(const bool isRecv);
~BaseMemoryUnit();
public:
OVERLAPPED overlapped;
WSABUF wsaBuf;
const bool isRecv; // true == recv, false == send
};
struct SendMemoryUnit /*: public BaseMemoryUnit*/
{
SendMemoryUnit();
~SendMemoryUnit();
//virtual ~SendMemoryUnit() override final;
public:
BaseMemoryUnit memoryUnit;
char dataBuf[NETWORK::MAX_SEND_SIZE];
};
struct ClientInfo /* : public BaseMemoryUnit */
{
ClientInfo(const _ClientIndexType key);
~ClientInfo();
//virtual ~BaseClientInfo() override;
public: // Fixed
BaseMemoryUnit memoryUnit;
_ClientIndexType key;
SOCKET socket;
bool isConnect = false;
const _ClientIndexType index;
char dataBuf[NETWORK::MAX_RECV_SIZE];
char loadedBuf[NETWORK::MAX_PACKET_SIZE];
_PacketSizeType loadedSize;
#pragma endregion
public: // Custom
std::atomic<bool> isLogin = false;
_PosType posX;
_PosType posY;
};
using _ClientType = ClientInfo; //
}using namespace MEMORY;
namespace PACKET_EXAMPLE
{
namespace TYPE
{
namespace SERVER_TO_CLIENT
{
enum
{
POSITION = 0,
LOGIN_TRUE = 1,
LOGIN_FAIL = 2,
PUT_OBJECT = 3,
ENUM_SIZE
};
}
namespace CLIENT_TO_SERVER
{
enum
{
MOVE = 0,
LOGIN = 1,
SIGN_UP = 2,
ATTACK = 3,
SKILL = 4,
USE_ITEM = 5,
TELEPORT = 6,
ENUM_SIZE
};
}
}
#pragma pack (push, 1)
namespace DATA
{
struct BasePacket
{
const _PacketSizeType size;
const _PacketType type;
BasePacket(const _PacketSizeType size, const _PacketType type) noexcept;
};
namespace SERVER_TO_CLIENT
{
struct LoginTrue : public BasePacket
{
const _ClientIndexType key;
char paddingBuffer[40];
LoginTrue(const _ClientIndexType key) noexcept;
};
struct PutObject : public BasePacket
{
const _ClientIndexType key;
const _PosType posX;
const _PosType posY;
unsigned int paddingBuffer;
PutObject(const _ClientIndexType key, const _PosType posX, const _PosType posY) noexcept;
};
struct Position : public BasePacket
{
const _ClientIndexType key;
const _PosType posX;
const _PosType posY;
Position(const _ClientIndexType key, const _PosType posX, const _PosType posY) noexcept;
};
}
namespace CLIENT_TO_SERVER
{
struct Move : public BasePacket
{
const _DirectionType dir;
Move(const _DirectionType dir) noexcept;
};
struct Login : public BasePacket
{
_IDType id[FRAMEWORK::MAX_ID_LENGTH];
Login(const _IDType* const pInNickname) noexcept;
};
struct SignUp : public BasePacket
{
_IDType id[FRAMEWORK::MAX_ID_LENGTH];
int pb0;
SignUp(const _IDType* const pInNickname) noexcept;
};
struct Attack : public BasePacket
{
unsigned char attackType; //0이면 기본공격, 1이면 스킬1, 2이면 스킬2
Attack(const unsigned char InAttackType ) noexcept;
};
struct Skill : public BasePacket
{
unsigned char skillType; //0이면 기본공격, 1이면 스킬1, 2이면 스킬2
Skill(const unsigned char InSkillType) noexcept;
};
struct UseItem : public BasePacket
{
unsigned char itemType; //0이면 기본공격, 1이면 스킬1, 2이면 스킬2
UseItem(const unsigned char InItemType) noexcept;
};
struct Teleport : public BasePacket
{
const _PosType posX; //0이면 기본공격, 1이면 스킬1, 2이면 스킬2
const _PosType posY;
Teleport(const _PosType posX, const _PosType posY) noexcept;
};
}
}
#pragma pack(pop)
}
| [
"koreagamemaker@gmail.com"
] | koreagamemaker@gmail.com |
176480111b7faa2420f156751b2079fad3c11b65 | c05ee947f4a79952aa7e6de9aa83678bd39863d7 | /loop_functions/basic_loop_functions.h | 1f164e03b4136348d4b328e563d2395443c7125b | [] | no_license | ChrisFrendo/FYP-Simulation | a16faa7955086092714f7e4822a2ec2e9c62b4c8 | 4dd044059deb519055084264287a7e7b5c062ee1 | refs/heads/main | 2023-06-03T08:52:24.201660 | 2021-06-26T11:04:27 | 2021-06-26T11:04:27 | 378,622,512 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,439 | h | #ifndef BASIC_LOOP_FUNCTIONS_H
#define BASIC_LOOP_FUNCTIONS_H
#include <argos3/core/simulator/loop_functions.h>
#include <argos3/core/simulator/entity/floor_entity.h>
#include <argos3/core/utility/math/range.h>
#include <argos3/core/utility/math/rng.h>
using namespace argos;
class CBasicLoopFunctions : public CLoopFunctions {
public:
CBasicLoopFunctions();
~CBasicLoopFunctions() override = default;
void Init(TConfigurationNode &t_tree) override;
void Reset() override;
void Destroy() override;
CColor GetFloorColor(const CVector2 &c_position_on_plane) override;
void PreStep() override;
void PostExperiment() override;
static UInt32 m_currentFoodInCache; // holds the current number of food items in the cache
static UInt32 m_maxFoodInCache; // holds the maximum number of food items in the cache
static UInt32 m_currentFoodInNest; // holds the current number of food items stored in the nest
enum ALGORITHM {
ALGO1 = 0,
ALGO2,
ALGO3,
INVALID
};
static ALGORITHM m_selectedAlgo;
private:
Real m_fFoodSquareRadius;
CRange<Real> m_cHarvestingArenaSideX, m_cHarvestingArenaSideY;
std::vector<CVector2> m_cFoodPos;
CFloorEntity *m_pcFloor;
CRandom::CRNG *m_pcRNG;
std::string m_strOutput;
std::ofstream m_cOutput;
UInt32 m_totalCachedFood; // holds total number of food placed in the cache
};
#endif | [
"chris.frendo.18@um.edu.mt"
] | chris.frendo.18@um.edu.mt |
1c0ccdbe1619c4940003cb4cebc85cabcf716928 | 398d62c4f6807e548d2b97cf0440bcafee635cea | /a_good_set.cpp | 694511362d274fe822d47162515e7d1a7f7d1b23 | [] | no_license | gujral1997/code_chef | 4c3b3f0d1a4b7afefaf6920ff5215e9d9def8a0d | 2f5c0d689a7a59a43921d11f37c892401a6ebe9e | refs/heads/master | 2021-09-02T08:31:38.784271 | 2018-01-01T01:32:29 | 2018-01-01T01:32:29 | 112,578,503 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 351 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long int lint;
int main(int argc, char const *argv[])
{
int t;
cin>>t;
while(t--)
{
int a,i=4,counter=2;
cin>>a;
if(a>=2)
{
cout<<1<<" "<<2<<" ";
}
else
{
cout<<1<<" ";
}
while(counter<a)
{
cout<<i<<" ";
i+=3;
counter++;
}
cout<<endl;
}
return 0;
} | [
"mastershady007@gmail.com"
] | mastershady007@gmail.com |
ac6668eb72b4d69174772d0dab5d006bc3226679 | 820c61849a45ed69f3e4636e2d3f0486304b5d46 | /Google Codejam/Codejam Problem A. Counting Sheep/main.cpp | 3e7db022000e283cb2857ccdd5157298c8f98fa1 | [] | no_license | Tanmoytkd/programming-projects | 1d842c994b6e2c546ab37a5378a823f9c9443c39 | 42c6f741d6da1e4cf787b1b4971a72ab2c2919e1 | refs/heads/master | 2021-08-07T18:00:43.530215 | 2021-06-04T11:18:27 | 2021-06-04T11:18:27 | 42,516,841 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 969 | cpp | #include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
#ifdef TKD
freopen("A-large.in", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int testcase;
cin >> testcase;
for(int i=1; i<=testcase; i++) {
bool check[10];
for(int j=0; j<10; j++) check[j]=false;
int number;
cin >> number;
cout << "Case #" << i << ": ";
if(number == 0) cout << "INSOMNIA" << endl;
else {
int counter=0, n=1, num;
while(counter != 10) {
num=number*n;
while(num) {
int dig=num%10;
num/=10;
if(check[dig]==false) {
counter++;
check[dig]=true;
}
}
if(counter==10) cout << number*n << endl;
n++;
}
}
}
return 0;
}
| [
"tanmoykrishnadas@gmail.com"
] | tanmoykrishnadas@gmail.com |
fd58eace55f87353188443c6ff79aac5aec78e00 | fa7f7337e829d358eea8e38b1cea41c2f7f2e60a | /Source/PacMan/Pac_GameMode.h | 2a27d86cfca4181e3fcc75de4525de96a8e135b4 | [] | no_license | kor-al/episodic-control-pacman | 1254d7217c08c0889c95d13a5aa09dcb39e5d6df | 5dc41307411fc0255c534aeb9082b58822e3a37a | refs/heads/master | 2021-01-01T16:35:53.968105 | 2017-07-20T17:54:54 | 2017-07-20T17:54:54 | 97,863,376 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 551 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/GameMode.h"
#include "Pac_GameMode.generated.h"
/**
*
*/
UCLASS()
class PACMAN_API APac_GameMode : public AGameMode
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "scoring")
int Player_Score;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "screenshots")
class AScreenCapturer* ScreenCapturer;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "game")
bool isVAE;
};
| [
"korinalice@gmail.com"
] | korinalice@gmail.com |
111f35639f594f729d6fd6380107f7e0ca419837 | 80885baabcdaa5e8d8abae31eebee72d072c2566 | /TimerCounter.cpp | cd4d427f5dca43ca5c1e2c4aa9b84ca5259c62d6 | [] | no_license | xiaoguosk/safeGeoRecommend | 28c97cd8a155601ed49955af3fae3cf2090848b3 | d294050cbf783b13803a87ce6240a3b615c2db47 | refs/heads/master | 2023-01-08T00:38:53.584801 | 2020-11-03T06:02:34 | 2020-11-03T06:02:34 | 309,245,038 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 487 | cpp | #include "TimerCounter.h"
#include <iostream>
using namespace std;
TimerCounter::TimerCounter(void)
{
QueryPerformanceFrequency(&freq);//获取主机CPU时钟频率
}
TimerCounter::~TimerCounter(void)
{
}
void TimerCounter::Start()
{
QueryPerformanceCounter(&startCount);//开始计时
}
void TimerCounter::Stop()
{
QueryPerformanceCounter(&endCount);//停止计时
dbTime = ((double)endCount.QuadPart - (double)startCount.QuadPart) / (double)freq.QuadPart;//获取时间差
} | [
"xiaoguosk@foxmail.com"
] | xiaoguosk@foxmail.com |
e447a7a8b5131fe9389ddc4dca3e2eea7ece3d46 | 10ecd7454a082e341eb60817341efa91d0c7fd0b | /SDK/BP_NPC_ReapersBones_Skeleton_InCage_parameters.h | 008c2833099805b8bee93c2aceb01628c6f52014 | [] | no_license | Blackstate/Sot-SDK | 1dba56354524572894f09ed27d653ae5f367d95b | cd73724ce9b46e3eb5b075c468427aa5040daf45 | refs/heads/main | 2023-04-10T07:26:10.255489 | 2021-04-23T01:39:08 | 2021-04-23T01:39:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 598 | h | #pragma once
// Name: SoT, Version: 2.1.0.1
#include "../SDK.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function BP_NPC_ReapersBones_Skeleton_InCage.BP_NPC_ReapersBones_Skeleton_InCage_C.UserConstructionScript
struct ABP_NPC_ReapersBones_Skeleton_InCage_C_UserConstructionScript_Params
{
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"ploszjanos9844@gmail.com"
] | ploszjanos9844@gmail.com |
f9d6009cd79c831768aa8b6e55342175998332ca | cd322b63899b2f6a80798cc34b9e9e4f0fc3c41e | /Accelerometer/src/mma8451_pi.h | 47c2bc10ae69ec981c0ffcfb3a58dd44a7ffea4c | [] | no_license | HUDView/HUDView | 3f9827b00fcc5b9d62147815cdfc0b6b5847f8ea | ddb9601d715e707e9082aa6ebe3b7d41b38f9c6c | refs/heads/develop | 2020-04-15T14:11:29.228987 | 2019-04-15T16:22:44 | 2019-04-15T16:22:44 | 164,745,310 | 1 | 1 | null | 2019-04-09T20:15:44 | 2019-01-08T22:40:08 | C | UTF-8 | C++ | false | false | 1,720 | h | #ifndef MMA8451_PI_INCLUDED
#define MMA8451_PI_INCLUDED
#ifdef __cplusplus
extern "C" {
#endif
///Structure that represent a mma8451 sensor. Get it from the initialise function and give it the other ones
typedef struct mma8451_
{
///File descriptor that point to an i2c device in /dev
int file;
///Address of the sensor on the i2c bus
unsigned char address;
///Current range setting
unsigned char range;
///raw data as sent by the sensor
unsigned char raw_data[6];
} mma8451;
///Default address of the sensor if you do nothing
#define MMA8451_DEFAULT_ADDR 0x1D
///Address if you pull down the address line
#define MMA8451_PULLDOWN_ADDR 0x1C
///Initialse the sensor at the given address
mma8451 mma8451_initialise(int device, int i2c_addr);
///Vector of 3 float
typedef struct mma8451_vector3_
{
float x, y, z;
} mma8451_vector3;
///write the content of register 0x01 to 0x06 to the output buffer.
void mma8451_get_raw_sample(mma8451* handle, char* output);
///get the current acceleration vector
mma8451_vector3 mma8451_get_acceleration_vector(mma8451* handle);
void mma8451_get_acceleration(mma8451* handle, mma8451_vector3* vector);
///set the "range" (aka:the max acceleration we register)
void mma8451_set_range(mma8451* handle, unsigned char range);
#ifdef __cplusplus
} //extern "C"
#endif
//Here we are on C++ linkage land
#ifdef __cplusplus
#include <iostream>
///operator overload ot print out the content of a mma8451_vector object if you are using C++
std::ostream& operator<< (std::ostream& out, const mma8451_vector3& vector)
{
out << "mma8451_vector3(" << vector.x << ", " << vector.y << ", " << vector.z << ")";
return out;
}
#endif
#endif
| [
"bdprisby@gmail.com"
] | bdprisby@gmail.com |
c67320bf77a4ed2680212c3b3e5be31f252bb5e4 | 7210b236415bea45ae6390fd828e523090b779d6 | /src/main.cpp | d3e46b18822da75d525058b0c2fcecb52c15c0e3 | [] | no_license | zhaoyu775885/FCEMS | 4cb0f2b8d2e80ed71352b5d7f2093f1fdb859e5a | d460672d2012cc29610531ba4618d45741ea10ec | refs/heads/master | 2019-01-21T16:13:32.533915 | 2017-03-16T01:48:14 | 2017-03-16T01:48:14 | 85,115,778 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,194 | cpp | #include <iostream>
#include "Mesh/Mesh.h"
#include "BasisFunction.h"
#include "BasicBEM.h"
#include "PostProcess.h"
#include "h2lib/cluster.h"
#include "h2lib/block.h"
#include "h2lib/hmatrix.h"
#include "h2lib/harith.h"
#include "h2lib/cluster.h"
#include "h2lib/hmatrix.h"
#include "FastBEM.h"
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;
#define DEBUG_ZMAT 0
#define FASTMETHOD 1
using namespace std;
int main(int argc, char * argv[])
{
string filenameNode("./input/feko/total_nodes.txt");
string filenameFace("./input/feko/all_surface.txt");
string filenameEdge("./input/feko/surface_edge.txt");
Mesh g_mesh(filenameNode, filenameEdge, filenameFace);
g_mesh.display_mesh_info();
BasisFunc g_basisfunc(g_mesh);
double freq = 3e8;
char integral_equation_type('p');
#if !FASTMETHOD
string filenameRCS("./output/b_rcs.csv");
BasicBem bem(g_basisfunc);
bem.build_euqation(freq, integral_equation_type);
#if DEBUG_ZMAT
bem.write_umat("output/b_exc.txt");
bem.write_zmat("output/b_zmat.txt");
#endif
bem.solve();
#else
string filenameRCS("./output/f_rcs.csv");
FastBemConf config = {100, 2, 1e-4};
FastBem bem(g_basisfunc, config);
auto t1 = Clock::now();
bem.build_equation(freq, integral_equation_type);
auto t2 = Clock::now();
cout << "rel. error is : " << scientific << bem.get_rel_error() << endl << endl;
cout << "max rank is : " << bem.get_max_rank() << endl;
cout << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() / 1000.0
<< " s" << endl;
// OpenGLLib plot(bem.get_hmatrix());
// plot.Display();
// bem.print_zmat("./output/z.txt");
cout << "print z over" << endl;
bem.direct_solve_vec();
bem.print_umat("./output/u.txt");
cout << "print u over" << endl;
auto t3 = Clock::now();
cout << std::chrono::duration_cast<std::chrono::milliseconds>(t3 - t2).count() / 1000.0
<< " s" << endl;
#endif // FASTMETHOD
PostProcess post( g_basisfunc, bem.export_data(), bem.get_nrow(), bem.get_nrhs(), freq, integral_equation_type );
post.gen_rcs(0, 360, 360);
post.write_rcs(filenameRCS);
return 0;
}
| [
"zhaoyu@Tank"
] | zhaoyu@Tank |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.