code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
# 96. Unique Binary Search Trees My Submissions QuestionEditorial Solution # Total Accepted: 84526 Total Submissions: 224165 Difficulty: Medium # Given n, how many structurally unique BST's (binary search trees) that store values 1...n? # # For example, # Given n = 3, there are a total of 5 unique BST's. # # 1 3 3 2 1 # \ / / / \ \ # 3 2 1 1 3 2 # / / \ \ # 2 1 2 3 # class Solution(object): def numTrees(self, n): """ :type n: int :rtype: int """ A = [0] * (n + 1) A[0] = 1 A[1] = 1 for i in xrange(2, n+1): for k in xrange(0, i): A[i] += A[k]*A[i-1-k] return A[n] # 4 4 4 4 4 # / / / / / # 1 3 3 2 1 # \ / / / \ \ # 3 2 1 1 3 2 # / / \ \ # 2 1 2 3 # # 1 3 3 2 1 2 # \ / \ / \ / \ \ / \ # 3 2 4 1 4 1 3 2 1 4 # / \ / \ \ \ / # 2 4 1 2 4 3 3 # \ # 4 # # Subscribe to see which companies asked this question # Analysis: # n = 0, 1 # n = 1, 1 # n = 2, 2 = (0,1) + (1,0) # n = 3, 5 = 2(0,2) + 2(2,0) + 1(1,1) # n = 4, 10 = (0,3), (1,2), (2,1), (0,3) # n = 5, class Solution(object): def numTrees(self, n): """ :type n: int :rtype: int """ if n == 0: return 0 res = [0 for x in xrange(0,n+1)] res[0], res[1] = 1, 1 for n in xrange(2, n+1): i, tmp = 0, 0 while i < n: tmp += res[i] * res[n-1-i] i += 1 res[n] = tmp return res[n] import unittest class TestSolution(unittest.TestCase): def test_0(self): self.assertEqual(Solution().numTrees(3), 5) def test_1(self): self.assertEqual(Solution().numTrees(2), 2) def test_2(self): self.assertEqual(Solution().numTrees(4), 14) if __name__ == "__main__": unittest.main()
shawncaojob/LC
QUESTIONS/96_unique_binary_search_trees.py
Python
gpl-3.0
2,402
/* kuroBox / naniBox Copyright (c) 2013 david morris-oliveros // naniBox.com This file is part of kuroBox / naniBox. kuroBox / naniBox is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. kuroBox / naniBox is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _naniBox_kuroBox_buttons #define _naniBox_kuroBox_buttons #include <ch.h> #include <hal.h> //----------------------------------------------------------------------------- int kuroBoxButtonsInit(void); //----------------------------------------------------------------------------- void btn_0_exti_cb(EXTDriver *extp, expchannel_t channel); void btn_1_exti_cb(EXTDriver *extp, expchannel_t channel); //----------------------------------------------------------------------------- bool_t is_btn_0_pressed(void); bool_t is_btn_1_pressed(void); #endif /* _naniBox_kuroBox_buttons */
naniBox/kuroBox_BurnIn
src/kb_buttons.h
C
gpl-3.0
1,427
// -*- mode: c++; indent-tabs-mode: nil; -*- // // Manta - Structural Variant and Indel Caller // Copyright (c) 2013-2015 Illumina, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // #include "boost/test/unit_test.hpp" #include "stage_manager.hh" //#define DEBUG_SM_TEST #ifdef DEBUG_SM_TEST #include <iostream> namespace { std::ostream& log_os(std::cerr); } #endif BOOST_AUTO_TEST_SUITE( test_stage_manager ) // create a standard stage size arrangement for testing: // // This returns a tree with: // stage 1 following 10 bases behind the root // stage 2 following 20 bases behind stage 1 // stage 3 following 20 bases behind the root // static stage_data get_test_stage_data() { stage_data sd; sd.add_stage(0); sd.add_stage(1,0,10); sd.add_stage(2,1,20); sd.add_stage(3,0,20); return sd; } static void stage_data_shift_test(const stage_data& sd, const int stage_id, const unsigned expect) { const unsigned result(sd.get_stage_id_shift(stage_id)); BOOST_CHECK_EQUAL(result,expect); } BOOST_AUTO_TEST_CASE( test_stage_data_dist ) { const stage_data sd(get_test_stage_data()); stage_data_shift_test(sd,0,0); stage_data_shift_test(sd,1,10); stage_data_shift_test(sd,2,30); stage_data_shift_test(sd,3,20); } BOOST_AUTO_TEST_CASE( test_stage_data_bad_parent ) { stage_data sd; BOOST_CHECK_THROW(sd.add_stage(1,0,10),std::exception); } BOOST_AUTO_TEST_CASE( test_stage_data_bad_id ) { stage_data sd; sd.add_stage(1); BOOST_CHECK_THROW(sd.get_stage_id_shift(0),std::exception); BOOST_CHECK_NO_THROW(sd.get_stage_id_shift(1)); BOOST_CHECK_THROW(sd.get_stage_id_shift(2),std::exception); } /// \brief Minimal pos_processor object used to test stage manager /// /// Note that this object is itself part of the test infrastructure by /// asserting: /// 1. ...that pos increases for each stage /// 2. TODO: ..the expected relationship (stage-to-root distance vs expect) /// of all stages as process_pos is called /// struct test_pos_processor : public pos_processor_base { // // TODO: finish setting up stage relationship checking... // // pos_processor wouldn't normally need this info, but we use // it to test expected stage position relationships // //test_pos_processor(const stage_data& sd, const pos_range& pr) // void process_pos(const int stage_no, const pos_t pos) { #ifdef DEBUG_SM_TEST log_os << "process_pos stage_no: " << stage_no << " pos: " << pos << "\n"; #endif // assert that pos for each stage does not repeat or decrease: spos_t::const_iterator i(stage_pos.find(stage_no)); if (i != stage_pos.end()) { BOOST_CHECK(pos > (i->second)); } stage_pos[stage_no] = pos; } typedef std::map<int,pos_t> spos_t; spos_t stage_pos; }; BOOST_AUTO_TEST_CASE( test_stage_manager ) { const stage_data sd(get_test_stage_data()); const pos_range report_range(0,60); test_pos_processor tpp; stage_manager sman(sd,report_range,tpp); sman.handle_new_pos_value(40); BOOST_CHECK_EQUAL(tpp.stage_pos[0],40); BOOST_CHECK_EQUAL(tpp.stage_pos[1],30); BOOST_CHECK_EQUAL(tpp.stage_pos[2],10); BOOST_CHECK_EQUAL(tpp.stage_pos[3],20); } BOOST_AUTO_TEST_CASE( test_stage_manager_reset ) { const stage_data sd(get_test_stage_data()); const pos_range report_range(0,60); test_pos_processor tpp; stage_manager sman(sd,report_range,tpp); sman.reset(); for (int i(0); i<4; ++i) { BOOST_CHECK_EQUAL(tpp.stage_pos[i],59); } } BOOST_AUTO_TEST_SUITE_END()
chapmanb/manta
src/c++/lib/blt_util/test/stage_manager_test.cpp
C++
gpl-3.0
4,333
<footer class="footer slide" id="footer" data-slide="6" style="min-height: 300px;height: auto;"> <div class="contentwrap row-fluid"> <div class="span4 blogs"> <span>Blogs:</span> <ul class="unstyled"> #if (!$Blog.getSiblings().isEmpty()) #foreach ($cur_Blog in $Blog.getSiblings()) <li> <a href="$cur_Blog.getData()" target="_blank"> <i class="icon-comment"></i>$cur_Blog.Nombre.getData() </a> </li> #end #end </ul> </div> <div class="span4 social"> <span>Síguenos en:</span> <ul class="og-grid"> <li> <a class="" href="$Facebook.getData()" target="_blank"> <i class="bg-hover-darkBlue fa fa-uce_facebook"></i> </a> </li> <li> <a href="$Twitter.getData()" target="_blank"> <i class="fa fa-uce_twiter"></i> </a> </li> <li> <a href="$YouTube.getData()" target="_blank"> <i class="bg-hover-red fa fa-uce_yotube"></i> </a> </li> #if (!$Otra_Red_Social.getSiblings().isEmpty()) #foreach ($cur_Otra_Red_Social in $Otra_Red_Social.getSiblings()) #if(!$cur_Otra_Red_Social.icono.getData()) <li> <a href="$cur_Otra_Red_Social.getData()" target="_blank"> <i class="bg-hover-red $cur_Otra_Red_Social.icono.getData()"></i> </a> </li> #end #end #end </ul> </div> <div class="span4 info"> <h5>Dirección</h5> <span>$direccion.getData()</span> <h5>Teléfonos:</h5> #if (!$Telefono.getSiblings().isEmpty()) #foreach ($cur_Telefono in $Telefono.getSiblings()) <span>$cur_Telefono.getData()</span> #end #end <h5>Horarios de atención:</h5> <span>Administración: $Horario_administracion.getData() </span> <span>Clases: $Horario_clases.getData()</span> </div> </div> <a class="scrollbut last" data-slide="1"></a> </footer>
Edgaru10/portal-uce
public_html/str_templates/fac/fac_contacto.html
HTML
gpl-3.0
2,526
/* * LedControl.cpp - A library for controling Leds with a MAX7219/MAX7221 * Copyright (c) 2007 Eberhard Fahle * * Feb. 2014 - Regis Blanchot - adapted to Pinguino * Feb. 2014 - Regis Blanchot - added scroll functions * * 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: * * 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. */ #ifndef LEDCONTROL_C #define LEDCONTROL_C #include <typedef.h> #include <const.h> #include <macro.h> #include <ledcontrol.h> //#include <stdio.h> #include <string.h> #include <digitalw.c> // digitalwrite #include <digitalp.c> // pinmode #include <delayms.c> //the opcodes for the MAX7221 and MAX7219 #define OP_NOOP 0 #define OP_DIGIT0 1 #define OP_DIGIT1 2 #define OP_DIGIT2 3 #define OP_DIGIT3 4 #define OP_DIGIT4 5 #define OP_DIGIT5 6 #define OP_DIGIT6 7 #define OP_DIGIT7 8 #define OP_DECODEMODE 9 #define OP_INTENSITY 10 #define OP_SCANLIMIT 11 #define OP_SHUTDOWN 12 #define OP_DISPLAYTEST 15 void LedControl_init(u8 dataPin, u8 clkPin, u8 csPin, u8 numDevices) { u8 i; LEDCONTROL_SPI_MOSI = dataPin; LEDCONTROL_SPI_CLK = clkPin; LEDCONTROL_SPI_CS = csPin; if(numDevices<=0 || numDevices>8 ) numDevices=8; maxDevices=numDevices; pinmode(LEDCONTROL_SPI_MOSI,OUTPUT); pinmode(LEDCONTROL_SPI_CLK,OUTPUT); pinmode(LEDCONTROL_SPI_CS,OUTPUT); digitalwrite(LEDCONTROL_SPI_CS,HIGH); LEDCONTROL_SPI_MOSI=dataPin; for(i=0;i<64;i++) status[i]=0x00; for(i=0;i<maxDevices;i++) { LedControl_spiTransfer(i,OP_DISPLAYTEST,0); //scanlimit is set to max on startup LedControl_setScanLimit(i,7); //decode is done in source LedControl_spiTransfer(i,OP_DECODEMODE,0); LedControl_clearDisplay(i); //we go into shutdown-mode on startup LedControl_shutdown(i,true); } } u8 LedControl_getDeviceCount() { return maxDevices; } void LedControl_shutdown(u8 matrix, boolean b) { if(matrix<0 || matrix>=maxDevices) return; if(b) LedControl_spiTransfer(matrix, OP_SHUTDOWN,0); else LedControl_spiTransfer(matrix, OP_SHUTDOWN,1); } void LedControl_setScanLimit(u8 matrix, u8 limit) { if(matrix<0 || matrix>=maxDevices) return; if(limit>=0 || limit<8) LedControl_spiTransfer(matrix, OP_SCANLIMIT,limit); } void LedControl_setIntensity(u8 matrix, u8 intensity) { if(matrix<0 || matrix>=maxDevices) return; if(intensity>=0 || intensity<16) LedControl_spiTransfer(matrix, OP_INTENSITY,intensity); } void LedControl_clearDisplay(u8 matrix) { u8 offset; u8 i; if(matrix<0 || matrix>=maxDevices) return; offset=matrix*8; for(i=0;i<8;i++) { status[offset+i]=0; LedControl_spiTransfer(matrix, i+1,status[offset+i]); } } void LedControl_clearAll() { u8 i; for (i=0;i<maxDevices;i++) LedControl_clearDisplay(i); } void LedControl_setLed(u8 matrix, u8 row, u8 column, boolean state) { u8 offset; u8 val=0x00; if(matrix<0 || matrix>=maxDevices) return; if(row<0 || row>7 || column<0 || column>7) return; offset=matrix*8; val=0b10000000 >> column; if(state) status[offset+row]=status[offset+row]|val; else { val=~val; status[offset+row]=status[offset+row]&val; } LedControl_spiTransfer(matrix, row+1,status[offset+row]); } void LedControl_setRow(u8 matrix, u8 row, u8 value) { u8 offset; if(matrix<0 || matrix>=maxDevices) return; if(row<0 || row>7) return; offset=matrix*8; status[offset+row]=value; LedControl_spiTransfer(matrix, row+1,status[offset+row]); } void LedControl_setColumn(u8 matrix, u8 col, u8 value) { u8 val; u8 row; if(matrix<0 || matrix>=maxDevices) return; if(col<0 || col>7) return; for(row=0;row<8;row++) { //val=value >> (7-row); val=value >> row; val=val & 0x01; LedControl_setLed(matrix,row,col,val); } } #if defined(SETDIGIT) void LedControl_setDigit(u8 matrix, u8 digit, u8 value, boolean dp) { u8 offset; u8 v; if(matrix<0 || matrix>=maxDevices) return; if(digit<0 || digit>7 || value>15) return; offset=matrix*8; v=charTable[value]; if(dp) v|=0b10000000; status[offset+digit]=v; LedControl_spiTransfer(matrix, digit+1,v); } #endif #if defined(SETCHAR) void LedControl_setChar(u8 matrix, u8 digit, char value, boolean dp) { u8 offset; u8 index,v; if(matrix<0 || matrix>=maxDevices) return; if(digit<0 || digit>7) return; offset=matrix*8; index=(u8)value; if(index >127) { //nothing define we use the space char value=32; } v=charTable[index]; if(dp) v|=0b10000000; status[offset+digit]=v; LedControl_spiTransfer(matrix, digit+1,v); } #endif void shiftOut(u8 dataPin, u8 clockPin, u8 bitOrder, u8 val) { u8 i; u8 bitMask; for (i = 0; i < 8; i++) { if (bitOrder == LSBFIRST) bitMask = (1 << i); else bitMask = (1 << (7 - i)); digitalwrite(dataPin, (val & bitMask) ? HIGH : LOW); digitalwrite(clockPin, HIGH); digitalwrite(clockPin, LOW); } } void LedControl_spiTransfer(u8 matrix, volatile u8 opcode, volatile u8 data) { //Create an array with the data to shift out u8 offset=matrix*2; u8 maxbytes=maxDevices*2; u8 i; for(i=0;i<maxbytes;i++) spidata[i]=(u8)0; //put our device data into the array spidata[offset+1]=opcode; spidata[offset]=data; //enable the line digitalwrite(LEDCONTROL_SPI_CS,LOW); //Now shift out the data for(i=maxbytes;i>0;i--) shiftOut(LEDCONTROL_SPI_MOSI,LEDCONTROL_SPI_CLK,MSBFIRST,spidata[i-1]); //latch the data onto the display digitalwrite(LEDCONTROL_SPI_CS,HIGH); } /* u8 LedControl_getCharArrayPosition(char input) { if ((input==' ')||(input=='+')) return 10; if (input==':') return 11; if (input=='-') return 12; if (input=='.') return 13; if ((input =='(')) return 14; //replace by 'ñ' if ((input >='0')&&(input <='9')) return (input-'0'); if ((input >='A')&&(input <='Z')) return (input-'A' + 15); if ((input >='a')&&(input <='z')) return (input-'a' + 15); return 13; } */ // Scroll Message // d'après : http://breizhmakers.over-blog.com/article-un-peu-d-animation-ou-le-scrolling-a-base-de-max7219-105669349.html #if defined(SCROLL) void LedControl_scroll(const char * displayString) { u8 nextchar; // next char to display u8 r; // current row u8 m; // current matrix u8 ascii; // current ASCII code u8 curchar; // current displayed char u8 offset; // nombre de bits à prendre dans l'octet suivant u8 row[8]; // u8 scrollmax = 8 * max(maxDevices, strlen(displayString)); // octet de départ curchar = scroll / 8; // nombre de bits à prendre dans l'octet suivant offset = scroll % 8; for (m=0; m<maxDevices; m++) { // for every line of the matrix for(r=0; r<8; r++) { row[r]=0; // matrix = current char shifted by offset ascii = displayString[curchar]-32; row[r] |= ( font[ascii][r] >> offset ); // si on n'est pas sur le premier bit d'un octet il faut prendre les bits qui restent à // afficher dans l'octet suivant if (offset > 0) { ascii = displayString[curchar+1]-32; if (ascii >= 0x20 && ascii <= 0x7F) { nextchar = font[ascii][r]; row[r] |= nextchar << (8-offset); } } } // Display the new matrix for (r=0; r<8; r++) LedControl_setColumn(m, 7-r, row[r]); curchar++; } // and wait a bit Delayms(50); // Do we cover the whole scroll area ? scroll = (scroll+1) % scrollmax; } #endif #if defined(WRITESTRING) void LedControl_writeString(const char * displayString) { u8 matrix=0; char c; while (c = *displayString++) { LedControl_displayChar(matrix, c); Delayms(300); //LedControl_clearAll(); //LedControl_clearDisplay(matrix); matrix++; if (matrix >= maxDevices) matrix=0; } Delayms(300); } #endif #if defined(WRITESTRING) || defined(DISPLAYCHAR) void LedControl_displayChar(u8 matrix, u8 charIndex) { u8 i; if (charIndex >= 0x20 && charIndex <= 0x7F) { for (i=0; i<8;i++) LedControl_setColumn(matrix, 7-i, font[charIndex-32][i]); } } #endif #endif /* LEDCONTROL_C */
TheLazyBastard/InXource
API/pinguino/libraries/ledcontrol.c
C
gpl-3.0
9,949
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe, erpnext from frappe.utils import flt, cstr, cint from frappe import _ from frappe.model.meta import get_field_precision from erpnext.accounts.doctype.budget.budget import validate_expense_against_budget from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import get_accounting_dimensions class ClosedAccountingPeriod(frappe.ValidationError): pass class StockAccountInvalidTransaction(frappe.ValidationError): pass def make_gl_entries(gl_map, cancel=False, adv_adj=False, merge_entries=True, update_outstanding='Yes', from_repost=False): if gl_map: if not cancel: validate_accounting_period(gl_map) gl_map = process_gl_map(gl_map, merge_entries) if gl_map and len(gl_map) > 1: save_entries(gl_map, adv_adj, update_outstanding, from_repost) else: frappe.throw(_("Incorrect number of General Ledger Entries found. You might have selected a wrong Account in the transaction.")) else: delete_gl_entries(gl_map, adv_adj=adv_adj, update_outstanding=update_outstanding) def validate_accounting_period(gl_map): accounting_periods = frappe.db.sql(""" SELECT ap.name as name FROM `tabAccounting Period` ap, `tabClosed Document` cd WHERE ap.name = cd.parent AND ap.company = %(company)s AND cd.closed = 1 AND cd.document_type = %(voucher_type)s AND %(date)s between ap.start_date and ap.end_date """, { 'date': gl_map[0].posting_date, 'company': gl_map[0].company, 'voucher_type': gl_map[0].voucher_type }, as_dict=1) if accounting_periods: frappe.throw(_("You can't create accounting entries in the closed accounting period {0}") .format(accounting_periods[0].name), ClosedAccountingPeriod) def process_gl_map(gl_map, merge_entries=True): if merge_entries: gl_map = merge_similar_entries(gl_map) for entry in gl_map: # toggle debit, credit if negative entry if flt(entry.debit) < 0: entry.credit = flt(entry.credit) - flt(entry.debit) entry.debit = 0.0 if flt(entry.debit_in_account_currency) < 0: entry.credit_in_account_currency = \ flt(entry.credit_in_account_currency) - flt(entry.debit_in_account_currency) entry.debit_in_account_currency = 0.0 if flt(entry.credit) < 0: entry.debit = flt(entry.debit) - flt(entry.credit) entry.credit = 0.0 if flt(entry.credit_in_account_currency) < 0: entry.debit_in_account_currency = \ flt(entry.debit_in_account_currency) - flt(entry.credit_in_account_currency) entry.credit_in_account_currency = 0.0 return gl_map def merge_similar_entries(gl_map): merged_gl_map = [] accounting_dimensions = get_accounting_dimensions() for entry in gl_map: # if there is already an entry in this account then just add it # to that entry same_head = check_if_in_list(entry, merged_gl_map, accounting_dimensions) if same_head: same_head.debit = flt(same_head.debit) + flt(entry.debit) same_head.debit_in_account_currency = \ flt(same_head.debit_in_account_currency) + flt(entry.debit_in_account_currency) same_head.credit = flt(same_head.credit) + flt(entry.credit) same_head.credit_in_account_currency = \ flt(same_head.credit_in_account_currency) + flt(entry.credit_in_account_currency) else: merged_gl_map.append(entry) # filter zero debit and credit entries merged_gl_map = filter(lambda x: flt(x.debit, 9)!=0 or flt(x.credit, 9)!=0, merged_gl_map) merged_gl_map = list(merged_gl_map) return merged_gl_map def check_if_in_list(gle, gl_map, dimensions=None): account_head_fieldnames = ['party_type', 'party', 'against_voucher', 'against_voucher_type', 'cost_center', 'project'] if dimensions: account_head_fieldnames = account_head_fieldnames + dimensions for e in gl_map: same_head = True if e.account != gle.account: same_head = False for fieldname in account_head_fieldnames: if cstr(e.get(fieldname)) != cstr(gle.get(fieldname)): same_head = False if same_head: return e def save_entries(gl_map, adv_adj, update_outstanding, from_repost=False): if not from_repost: validate_account_for_perpetual_inventory(gl_map) validate_cwip_accounts(gl_map) round_off_debit_credit(gl_map) for entry in gl_map: make_entry(entry, adv_adj, update_outstanding, from_repost) # check against budget if not from_repost: validate_expense_against_budget(entry) def make_entry(args, adv_adj, update_outstanding, from_repost=False): args.update({"doctype": "GL Entry"}) gle = frappe.get_doc(args) gle.flags.ignore_permissions = 1 gle.flags.from_repost = from_repost gle.insert() gle.run_method("on_update_with_args", adv_adj, update_outstanding, from_repost) gle.submit() def validate_account_for_perpetual_inventory(gl_map): if cint(erpnext.is_perpetual_inventory_enabled(gl_map[0].company)) \ and gl_map[0].voucher_type=="Journal Entry": aii_accounts = [d[0] for d in frappe.db.sql("""select name from tabAccount where account_type = 'Stock' and is_group=0""")] for entry in gl_map: if entry.account in aii_accounts: frappe.throw(_("Account: {0} can only be updated via Stock Transactions") .format(entry.account), StockAccountInvalidTransaction) def validate_cwip_accounts(gl_map): if not cint(frappe.db.get_value("Asset Settings", None, "disable_cwip_accounting")) \ and gl_map[0].voucher_type == "Journal Entry": cwip_accounts = [d[0] for d in frappe.db.sql("""select name from tabAccount where account_type = 'Capital Work in Progress' and is_group=0""")] for entry in gl_map: if entry.account in cwip_accounts: frappe.throw(_("Account: <b>{0}</b> is capital Work in progress and can not be updated by Journal Entry").format(entry.account)) def round_off_debit_credit(gl_map): precision = get_field_precision(frappe.get_meta("GL Entry").get_field("debit"), currency=frappe.get_cached_value('Company', gl_map[0].company, "default_currency")) debit_credit_diff = 0.0 for entry in gl_map: entry.debit = flt(entry.debit, precision) entry.credit = flt(entry.credit, precision) debit_credit_diff += entry.debit - entry.credit debit_credit_diff = flt(debit_credit_diff, precision) if gl_map[0]["voucher_type"] in ("Journal Entry", "Payment Entry"): allowance = 5.0 / (10**precision) else: allowance = .5 if abs(debit_credit_diff) >= allowance: frappe.throw(_("Debit and Credit not equal for {0} #{1}. Difference is {2}.") .format(gl_map[0].voucher_type, gl_map[0].voucher_no, debit_credit_diff)) elif abs(debit_credit_diff) >= (1.0 / (10**precision)): make_round_off_gle(gl_map, debit_credit_diff, precision) def make_round_off_gle(gl_map, debit_credit_diff, precision): round_off_account, round_off_cost_center = get_round_off_account_and_cost_center(gl_map[0].company) round_off_account_exists = False round_off_gle = frappe._dict() for d in gl_map: if d.account == round_off_account: round_off_gle = d if d.debit_in_account_currency: debit_credit_diff -= flt(d.debit_in_account_currency) else: debit_credit_diff += flt(d.credit_in_account_currency) round_off_account_exists = True if round_off_account_exists and abs(debit_credit_diff) <= (1.0 / (10**precision)): gl_map.remove(round_off_gle) return if not round_off_gle: for k in ["voucher_type", "voucher_no", "company", "posting_date", "remarks", "is_opening"]: round_off_gle[k] = gl_map[0][k] round_off_gle.update({ "account": round_off_account, "debit_in_account_currency": abs(debit_credit_diff) if debit_credit_diff < 0 else 0, "credit_in_account_currency": debit_credit_diff if debit_credit_diff > 0 else 0, "debit": abs(debit_credit_diff) if debit_credit_diff < 0 else 0, "credit": debit_credit_diff if debit_credit_diff > 0 else 0, "cost_center": round_off_cost_center, "party_type": None, "party": None, "against_voucher_type": None, "against_voucher": None }) if not round_off_account_exists: gl_map.append(round_off_gle) def get_round_off_account_and_cost_center(company): round_off_account, round_off_cost_center = frappe.get_cached_value('Company', company, ["round_off_account", "round_off_cost_center"]) or [None, None] if not round_off_account: frappe.throw(_("Please mention Round Off Account in Company")) if not round_off_cost_center: frappe.throw(_("Please mention Round Off Cost Center in Company")) return round_off_account, round_off_cost_center def delete_gl_entries(gl_entries=None, voucher_type=None, voucher_no=None, adv_adj=False, update_outstanding="Yes"): from erpnext.accounts.doctype.gl_entry.gl_entry import validate_balance_type, \ check_freezing_date, update_outstanding_amt, validate_frozen_account if not gl_entries: gl_entries = frappe.db.sql(""" select account, posting_date, party_type, party, cost_center, fiscal_year,voucher_type, voucher_no, against_voucher_type, against_voucher, cost_center, company from `tabGL Entry` where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no), as_dict=True) if gl_entries: check_freezing_date(gl_entries[0]["posting_date"], adv_adj) frappe.db.sql("""delete from `tabGL Entry` where voucher_type=%s and voucher_no=%s""", (voucher_type or gl_entries[0]["voucher_type"], voucher_no or gl_entries[0]["voucher_no"])) for entry in gl_entries: validate_frozen_account(entry["account"], adv_adj) validate_balance_type(entry["account"], adv_adj) if not adv_adj: validate_expense_against_budget(entry) if entry.get("against_voucher") and update_outstanding == 'Yes' and not adv_adj: update_outstanding_amt(entry["account"], entry.get("party_type"), entry.get("party"), entry.get("against_voucher_type"), entry.get("against_voucher"), on_cancel=True)
Zlash65/erpnext
erpnext/accounts/general_ledger.py
Python
gpl-3.0
9,852
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Service * @subpackage DeveloperGarden * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: UpdateConferenceResponse.php 24594 2012-01-05 21:27:01Z matthew $ */ /** * @see Zend_Service_DeveloperGarden_Response_ConferenceCall_ConferenceCallAbstract */ //require_once 'Zend/Service/DeveloperGarden/Response/ConferenceCall/ConferenceCallAbstract.php'; /** * @category Zend * @package Zend_Service * @subpackage DeveloperGarden * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @author Marco Kaiser * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Service_DeveloperGarden_Response_ConferenceCall_UpdateConferenceResponse extends Zend_Service_DeveloperGarden_Response_ConferenceCall_ConferenceCallAbstract { /** * response data * * @codingStandardsIgnoreFile * @var Zend_Service_DeveloperGarden_Response_ConferenceCall_CCSResponseType */ public $CCSResponse = null; }
sadiqdon/cycommerce
common/lib/Zend/Service/DeveloperGarden/Response/ConferenceCall/UpdateConferenceResponse.php
PHP
gpl-3.0
1,636
! copyright info: ! ! @Copyright 2001 ! Fireball Committee ! Brigham Young University - James P. Lewis, Chair ! Arizona State University - Otto F. Sankey ! University of Regensburg - Juergen Fritsch ! Universidad de Madrid - Jose Ortega ! Other contributors, past and present: ! Auburn University - Jian Jun Dong ! Arizona State University - Gary B. Adams ! Arizona State University - Kevin Schmidt ! Arizona State University - John Tomfohr ! Lawrence Livermore National Laboratory - Kurt Glaesemann ! Motorola, Physical Sciences Research Labs - Alex Demkov ! Motorola, Physical Sciences Research Labs - Jun Wang ! Ohio University - Dave Drabold ! ! RESTRICTED RIGHTS LEGEND ! Use, duplication, or disclosure of this software and its documentation ! by the Government is subject to restrictions as set forth in ! subdivision ! { (b) (3) (ii) } of the Rights in Technical Data and Computer Software ! clause at 52.227-7013. ! integrate_hpsi.f90 ! Program Description ! =========================================================================== ! This routines integrates the Schroedinger equation for a trial binding ! energy. The number of nodes are returned and the discontinuity in the ! logarithmic derivative. ! ! =========================================================================== ! Code written by: ! James P. Lewis ! Department of Physics and Astronomy ! Brigham Young University ! N233 ESC P.O. Box 24658 ! Provo, UT 841184602-4658 ! FAX 801-422-2265 ! Office telephone 801-422-7444 ! =========================================================================== ! ! Program Declaration ! =========================================================================== subroutine integrate_hpsi (mesh, l, rcutoff, ebind, v, node, alnd) use precision implicit none ! Argument Declaration and Description ! =========================================================================== ! Input integer, intent (in) :: l integer, intent (in) :: mesh real(kind=long), intent (in) :: ebind real(kind=long), intent (in) :: rcutoff real(kind=long), intent (in), dimension (mesh) :: v ! Output integer, intent (out) :: node real(kind=long), intent (out) :: alnd ! Local Parameters and Data Declaration ! =========================================================================== ! Local Variable Declaration and Description ! =========================================================================== integer imatch integer ipoint integer istart real(kind=long) dr real(kind=long) h12 real(kind=long) u1, u2, u3 real(kind=long) v1, v2, v3 real(kind=long), dimension (:), allocatable :: r real(kind=long), dimension (:), allocatable :: v_ang ! Allocate Arrays ! =========================================================================== allocate (r(mesh)) allocate (v_ang(mesh)) ! Procedure ! =========================================================================== dr = rcutoff/(mesh - 1) h12 = dr**2/12.0d0 do ipoint = 2, mesh r(ipoint) = (ipoint - 1)*dr end do v_ang(1) = 0.0d0 v_ang(2:mesh) = l*(l + 1.0d0)/r(2:mesh)**2 ! imatch = matching point for the integration ! Why is it multiplied by such an odd number such as 0.53 - is this supposed ! to be abohr? istart = 1 imatch = mesh*0.53d0 ! Initialize node counter node = 0 ! Integrate out from origin u1 = 0.0d0 u2 = dr v1 = 0.0d0 v2 = v(istart+1) + v_ang(istart+1) + ebind do ipoint = istart + 2, imatch v3 = v(ipoint) + v_ang(ipoint) + ebind u3 = (u2*(2.0d0 + 10.0d0*h12*v2) - u1*(1.0d0 - h12*v1)) & & /(1.0d0 - h12*v3) if (sign(1.0d0,u3) .ne. sign(1.0d0,u2)) node = node + 1 u1 = u2 u2 = u3 v1 = v2 v2 = v3 end do v3 = v(imatch+1) + v_ang(imatch+1) + ebind u3 = (u2*(2.0d0 + 10.0d0*h12*v2) - u1*(1.0d0 - h12*v1))/(1.0d0 - h12*v3) alnd = (u3 - u1)/(2.0d0*dr*u2) ! Now integrate in from rmax u1 = 0.0d0 u2 = dr v1 = v(mesh) + v_ang(mesh) + ebind v2 = v(mesh-1) + v_ang(mesh-1) + ebind do ipoint = mesh-2, imatch, -1 v3 = v(ipoint) + v_ang(ipoint) + ebind u3 = (u2*(2.0d0 + 10.0d0*h12*v2) - u1*(1.0d0 - h12*v1)) & & /(1.0d0 - h12*v3) if (sign(1.0d0,u3) .ne. sign(1.0d0,u2)) node = node + 1 u1 = u2 u2 = u3 v1 = v2 v2 = v3 end do v3 = v(mesh-imatch-1) + v_ang(mesh-imatch-1) + ebind u3 = (u2*(2.0d0 + 10.0d0*h12*v2) - u1*(1.0d0 - h12*v1))/(1.0d0 - h12*v3) ! Calculate discontinuity in log derivative - it may look like this is lower ! order, but matching these actually matches the solution exactly alnd = alnd + (u3 - u1)/(2.0d0*dr*u2) ! Deallocate Arrays ! =========================================================================== deallocate (r) deallocate (v_ang) ! Format Statements ! =========================================================================== return end
fireball-QMD/begin
begin_rcatms/RCATMS/integrate_hpsi.f90
FORTRAN
gpl-3.0
5,318
<h1>TiTouchImageView Module</h1> <p>================</p> <p>Titanium native module wrapper for TouchImageView: https://github.com/MikeOrtiz/TouchImageView</p> <p>Do you like pinching and zooming on iOS? Wish it just worked on Android too? Here you go!</p> <h2>Get it <a href="http://gitt.io/component/org.iotashan.TiTouchImageView"><img alt="gitTio" src="http://gitt.io/badge.png" /></a></h2> <p>Download the latest distribution ZIP-file and consult the <a href="http://docs.appcelerator.com/titanium/latest/#!/guide/Using_a_Module">Titanium Documentation</a> on how install it, or simply use the <a href="http://gitt.io/cli">gitTio CLI</a>:</p> <p><code>$ gittio install org.iotashan.TiTouchImageView</code></p> <h2>Referencing the module in your Ti mobile application</h2> <p>Simply add the following lines to your <code>tiapp.xml</code> file:</p> <p><modules> <module platform="android">org.iotashan.titouchimageview</module> </modules></p> <p>To use your module in code, you will need to require it.</p> <pre><code>var TiTouchImageView = require('org.iotashan.TiTouchImageView'); var myView = TiTouchImageView.createView(); </code></pre> <h2>API Properties</h2> <h3>image</h3> <p>Accepts a string path to a local file, or a TiBlob image object.</p> <h3>maxZoom</h3> <p>Maximum zoom value, as a decimal. "5.5" means you can zoom in 550%</p> <h3>minZoom</h3> <p>Minimum zoom value, as a decimal. "0.5" means you can zoom out to 50%</p> <h3>zoom</h3> <p>Zoom value for the view, as a decimal. Want to zoom to 300%? Set the value to 3.</p> <h2>API Methods</h2> <h3>createView(props)</h3> <p>Accepts a dictonary of properties. TiTouchImageView extends TiUIView, so you can set other properties like top/left, backgroundColor, etc. Returns the view.</p> <h3>resetZoom()</h3> <p>Resets the zoom to the default value for the view.</p> <h3>scrollTo(x,y)</h3> <p>Scrolls the view to the point specified.</p> <h3>getCurrentZoom()</h3> <p>Returns the current zoom level as a float.</p> <h3>getScrollPosition()</h3> <p>Returns the current scroll position as point co-ordinates (x,y)</p>
ClinicalSoftwareSolutions/WellsScoreCalc
modules/android/org.iotashan.titouchimageview/1.0.2/documentation/index.html
HTML
gpl-3.0
2,081
/* * Copyright 2015 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ package org.appspot.apprtc; import android.app.Activity; import android.app.AlertDialog; import android.app.FragmentTransaction; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager.LayoutParams; import android.widget.Toast; import org.appspot.apprtc.AppRTCClient.RoomConnectionParameters; import org.appspot.apprtc.AppRTCClient.SignalingParameters; import org.appspot.apprtc.PeerConnectionClient.PeerConnectionParameters; import org.appspot.apprtc.util.LooperExecutor; import org.webrtc.EglBase; import org.webrtc.IceCandidate; import org.webrtc.PeerConnectionFactory; import org.webrtc.RendererCommon.ScalingType; import org.webrtc.SessionDescription; import org.webrtc.StatsReport; import org.webrtc.SurfaceViewRenderer; /** * Activity for peer connection call setup, call waiting * and call view. */ public class CallActivity extends Activity implements AppRTCClient.SignalingEvents, PeerConnectionClient.PeerConnectionEvents, CallFragment.OnCallEvents { public static final String EXTRA_ROOMID = "org.appspot.apprtc.ROOMID"; public static final String EXTRA_LOOPBACK = "org.appspot.apprtc.LOOPBACK"; public static final String EXTRA_VIDEO_CALL = "org.appspot.apprtc.VIDEO_CALL"; public static final String EXTRA_VIDEO_WIDTH = "org.appspot.apprtc.VIDEO_WIDTH"; public static final String EXTRA_VIDEO_HEIGHT = "org.appspot.apprtc.VIDEO_HEIGHT"; public static final String EXTRA_VIDEO_FPS = "org.appspot.apprtc.VIDEO_FPS"; public static final String EXTRA_VIDEO_CAPTUREQUALITYSLIDER_ENABLED = "org.appsopt.apprtc.VIDEO_CAPTUREQUALITYSLIDER"; public static final String EXTRA_VIDEO_BITRATE = "org.appspot.apprtc.VIDEO_BITRATE"; public static final String EXTRA_VIDEOCODEC = "org.appspot.apprtc.VIDEOCODEC"; public static final String EXTRA_HWCODEC_ENABLED = "org.appspot.apprtc.HWCODEC"; public static final String EXTRA_CAPTURETOTEXTURE_ENABLED = "org.appspot.apprtc.CAPTURETOTEXTURE"; public static final String EXTRA_AUDIO_BITRATE = "org.appspot.apprtc.AUDIO_BITRATE"; public static final String EXTRA_AUDIOCODEC = "org.appspot.apprtc.AUDIOCODEC"; public static final String EXTRA_NOAUDIOPROCESSING_ENABLED = "org.appspot.apprtc.NOAUDIOPROCESSING"; public static final String EXTRA_AECDUMP_ENABLED = "org.appspot.apprtc.AECDUMP"; public static final String EXTRA_OPENSLES_ENABLED = "org.appspot.apprtc.OPENSLES"; public static final String EXTRA_DISABLE_BUILT_IN_AEC = "org.appspot.apprtc.DISABLE_BUILT_IN_AEC"; public static final String EXTRA_DISPLAY_HUD = "org.appspot.apprtc.DISPLAY_HUD"; public static final String EXTRA_TRACING = "org.appspot.apprtc.TRACING"; public static final String EXTRA_CMDLINE = "org.appspot.apprtc.CMDLINE"; public static final String EXTRA_RUNTIME = "org.appspot.apprtc.RUNTIME"; private static final String TAG = "CallRTCClient"; // List of mandatory application permissions. private static final String[] MANDATORY_PERMISSIONS = { "android.permission.MODIFY_AUDIO_SETTINGS", "android.permission.RECORD_AUDIO", "android.permission.INTERNET" }; // Peer connection statistics callback period in ms. private static final int STAT_CALLBACK_PERIOD = 1000; // Local preview screen position before call is connected. private static final int LOCAL_X_CONNECTING = 0; private static final int LOCAL_Y_CONNECTING = 0; private static final int LOCAL_WIDTH_CONNECTING = 100; private static final int LOCAL_HEIGHT_CONNECTING = 100; // Local preview screen position after call is connected. private static final int LOCAL_X_CONNECTED = 72; private static final int LOCAL_Y_CONNECTED = 72; private static final int LOCAL_WIDTH_CONNECTED = 25; private static final int LOCAL_HEIGHT_CONNECTED = 25; // Remote video screen position private static final int REMOTE_X = 0; private static final int REMOTE_Y = 0; private static final int REMOTE_WIDTH = 100; private static final int REMOTE_HEIGHT = 100; private PeerConnectionClient peerConnectionClient = null; private AppRTCClient appRtcClient; private SignalingParameters signalingParameters; private AppRTCAudioManager audioManager = null; private EglBase rootEglBase; private SurfaceViewRenderer localRender; private SurfaceViewRenderer remoteRender; private PercentFrameLayout localRenderLayout; private PercentFrameLayout remoteRenderLayout; private ScalingType scalingType; private Toast logToast; private boolean commandLineRun; private int runTimeMs; private boolean activityRunning; private RoomConnectionParameters roomConnectionParameters; private PeerConnectionParameters peerConnectionParameters; private boolean iceConnected; private boolean isError; private boolean callControlFragmentVisible = true; private long callStartedTimeMs = 0; private boolean micEnabled = true; // Controls private CallFragment callFragment; private HudFragment hudFragment; private CpuMonitor cpuMonitor; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Thread.setDefaultUncaughtExceptionHandler( new UnhandledExceptionHandler(this)); // Set window styles for fullscreen-window size. Needs to be done before // adding content. requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().addFlags( LayoutParams.FLAG_FULLSCREEN | LayoutParams.FLAG_KEEP_SCREEN_ON | LayoutParams.FLAG_DISMISS_KEYGUARD | LayoutParams.FLAG_SHOW_WHEN_LOCKED | LayoutParams.FLAG_TURN_SCREEN_ON); getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); setContentView(R.layout.activity_call); iceConnected = false; signalingParameters = null; scalingType = ScalingType.SCALE_ASPECT_FILL; // Create UI controls. localRender = (SurfaceViewRenderer) findViewById(R.id.local_video_view); remoteRender = (SurfaceViewRenderer) findViewById(R.id.remote_video_view); localRenderLayout = (PercentFrameLayout) findViewById(R.id.local_video_layout); remoteRenderLayout = (PercentFrameLayout) findViewById(R.id.remote_video_layout); callFragment = new CallFragment(); hudFragment = new HudFragment(); // Show/hide call control fragment on view click. View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View view) { toggleCallControlFragmentVisibility(); } }; localRender.setOnClickListener(listener); remoteRender.setOnClickListener(listener); // Create video renderers. rootEglBase = EglBase.create(); localRender.init(rootEglBase.getEglBaseContext(), null); remoteRender.init(rootEglBase.getEglBaseContext(), null); localRender.setZOrderMediaOverlay(true); updateVideoView(); // Check for mandatory permissions. for (String permission : MANDATORY_PERMISSIONS) { if (checkCallingOrSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { logAndToast("Permission " + permission + " is not granted"); setResult(RESULT_CANCELED); finish(); return; } } // Get Intent parameters. final Intent intent = getIntent(); Uri roomUri = intent.getData(); if (roomUri == null) { logAndToast(getString(R.string.missing_url)); Log.e(TAG, "Didn't get any URL in intent!"); setResult(RESULT_CANCELED); finish(); return; } String roomId = intent.getStringExtra(EXTRA_ROOMID); if (roomId == null || roomId.length() == 0) { logAndToast(getString(R.string.missing_url)); Log.e(TAG, "Incorrect room ID in intent!"); setResult(RESULT_CANCELED); finish(); return; } boolean loopback = intent.getBooleanExtra(EXTRA_LOOPBACK, false); boolean tracing = intent.getBooleanExtra(EXTRA_TRACING, false); peerConnectionParameters = new PeerConnectionParameters( intent.getBooleanExtra(EXTRA_VIDEO_CALL, true), loopback, tracing, intent.getIntExtra(EXTRA_VIDEO_WIDTH, 0), intent.getIntExtra(EXTRA_VIDEO_HEIGHT, 0), intent.getIntExtra(EXTRA_VIDEO_FPS, 0), intent.getIntExtra(EXTRA_VIDEO_BITRATE, 0), intent.getStringExtra(EXTRA_VIDEOCODEC), intent.getBooleanExtra(EXTRA_HWCODEC_ENABLED, true), intent.getBooleanExtra(EXTRA_CAPTURETOTEXTURE_ENABLED, false), intent.getIntExtra(EXTRA_AUDIO_BITRATE, 0), intent.getStringExtra(EXTRA_AUDIOCODEC), intent.getBooleanExtra(EXTRA_NOAUDIOPROCESSING_ENABLED, false), intent.getBooleanExtra(EXTRA_AECDUMP_ENABLED, false), intent.getBooleanExtra(EXTRA_OPENSLES_ENABLED, false), intent.getBooleanExtra(EXTRA_DISABLE_BUILT_IN_AEC, false)); commandLineRun = intent.getBooleanExtra(EXTRA_CMDLINE, false); runTimeMs = intent.getIntExtra(EXTRA_RUNTIME, 0); // Create connection client. Use DirectRTCClient if room name is an IP otherwise use the // standard WebSocketRTCClient. if (loopback || !DirectRTCClient.IP_PATTERN.matcher(roomId).matches()) { appRtcClient = new WebSocketRTCClient(this, new LooperExecutor()); } else { Log.i(TAG, "Using DirectRTCClient because room name looks like an IP."); appRtcClient = new DirectRTCClient(this); } // Create connection parameters. roomConnectionParameters = new RoomConnectionParameters( roomUri.toString(), roomId, loopback); // Create CPU monitor cpuMonitor = new CpuMonitor(this); hudFragment.setCpuMonitor(cpuMonitor); // Send intent arguments to fragments. callFragment.setArguments(intent.getExtras()); hudFragment.setArguments(intent.getExtras()); // Activate call and HUD fragments and start the call. FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(R.id.call_fragment_container, callFragment); ft.add(R.id.hud_fragment_container, hudFragment); ft.commit(); startCall(); // For command line execution run connection for <runTimeMs> and exit. if (commandLineRun && runTimeMs > 0) { (new Handler()).postDelayed(new Runnable() { @Override public void run() { disconnect(); } }, runTimeMs); } peerConnectionClient = PeerConnectionClient.getInstance(); if (loopback) { PeerConnectionFactory.Options options = new PeerConnectionFactory.Options(); options.networkIgnoreMask = 0; peerConnectionClient.setPeerConnectionFactoryOptions(options); } peerConnectionClient.createPeerConnectionFactory( CallActivity.this, peerConnectionParameters, CallActivity.this); } // Activity interfaces @Override public void onPause() { super.onPause(); activityRunning = false; if (peerConnectionClient != null) { peerConnectionClient.stopVideoSource(); } cpuMonitor.pause(); } @Override public void onResume() { super.onResume(); activityRunning = true; if (peerConnectionClient != null) { peerConnectionClient.startVideoSource(); } cpuMonitor.resume(); } @Override protected void onDestroy() { disconnect(); if (logToast != null) { logToast.cancel(); } activityRunning = false; rootEglBase.release(); super.onDestroy(); } // CallFragment.OnCallEvents interface implementation. @Override public void onCallHangUp() { disconnect(); } @Override public void onCameraSwitch() { if (peerConnectionClient != null) { peerConnectionClient.switchCamera(); } } @Override public void onVideoScalingSwitch(ScalingType scalingType) { this.scalingType = scalingType; updateVideoView(); } @Override public void onCaptureFormatChange(int width, int height, int framerate) { if (peerConnectionClient != null) { peerConnectionClient.changeCaptureFormat(width, height, framerate); } } @Override public boolean onToggleMic() { if (peerConnectionClient != null) { micEnabled = !micEnabled; peerConnectionClient.setAudioEnabled(micEnabled); } return micEnabled; } // Helper functions. private void toggleCallControlFragmentVisibility() { if (!iceConnected || !callFragment.isAdded()) { return; } // Show/hide call control fragment callControlFragmentVisible = !callControlFragmentVisible; FragmentTransaction ft = getFragmentManager().beginTransaction(); if (callControlFragmentVisible) { ft.show(callFragment); ft.show(hudFragment); } else { ft.hide(callFragment); ft.hide(hudFragment); } ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } private void updateVideoView() { remoteRenderLayout.setPosition(REMOTE_X, REMOTE_Y, REMOTE_WIDTH, REMOTE_HEIGHT); remoteRender.setScalingType(scalingType); remoteRender.setMirror(false); if (iceConnected) { localRenderLayout.setPosition( LOCAL_X_CONNECTED, LOCAL_Y_CONNECTED, LOCAL_WIDTH_CONNECTED, LOCAL_HEIGHT_CONNECTED); localRender.setScalingType(ScalingType.SCALE_ASPECT_FIT); } else { localRenderLayout.setPosition( LOCAL_X_CONNECTING, LOCAL_Y_CONNECTING, LOCAL_WIDTH_CONNECTING, LOCAL_HEIGHT_CONNECTING); localRender.setScalingType(scalingType); } localRender.setMirror(true); localRender.requestLayout(); remoteRender.requestLayout(); } private void startCall() { if (appRtcClient == null) { Log.e(TAG, "AppRTC client is not allocated for a call."); return; } callStartedTimeMs = System.currentTimeMillis(); // Start room connection. logAndToast(getString(R.string.connecting_to, roomConnectionParameters.roomUrl)); appRtcClient.connectToRoom(roomConnectionParameters); // Create and audio manager that will take care of audio routing, // audio modes, audio device enumeration etc. audioManager = AppRTCAudioManager.create(this, new Runnable() { // This method will be called each time the audio state (number and // type of devices) has been changed. @Override public void run() { onAudioManagerChangedState(); } } ); // Store existing audio settings and change audio mode to // MODE_IN_COMMUNICATION for best possible VoIP performance. Log.d(TAG, "Initializing the audio manager..."); audioManager.init(); } // Should be called from UI thread private void callConnected() { final long delta = System.currentTimeMillis() - callStartedTimeMs; Log.i(TAG, "Call connected: delay=" + delta + "ms"); if (peerConnectionClient == null || isError) { Log.w(TAG, "Call is connected in closed or error state"); return; } // Update video view. updateVideoView(); // Enable statistics callback. peerConnectionClient.enableStatsEvents(true, STAT_CALLBACK_PERIOD); } private void onAudioManagerChangedState() { // TODO(henrika): disable video if AppRTCAudioManager.AudioDevice.EARPIECE // is active. } // Disconnect from remote resources, dispose of local resources, and exit. private void disconnect() { activityRunning = false; if (appRtcClient != null) { appRtcClient.disconnectFromRoom(); appRtcClient = null; } if (peerConnectionClient != null) { peerConnectionClient.close(); peerConnectionClient = null; } if (localRender != null) { localRender.release(); localRender = null; } if (remoteRender != null) { remoteRender.release(); remoteRender = null; } if (audioManager != null) { audioManager.close(); audioManager = null; } if (iceConnected && !isError) { setResult(RESULT_OK); } else { setResult(RESULT_CANCELED); } finish(); } private void disconnectWithErrorMessage(final String errorMessage) { if (commandLineRun || !activityRunning) { Log.e(TAG, "Critical error: " + errorMessage); disconnect(); } else { new AlertDialog.Builder(this) .setTitle(getText(R.string.channel_error_title)) .setMessage(errorMessage) .setCancelable(false) .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); disconnect(); } }).create().show(); } } // Log |msg| and Toast about it. private void logAndToast(String msg) { Log.d(TAG, msg); if (logToast != null) { logToast.cancel(); } logToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT); logToast.show(); } private void reportError(final String description) { runOnUiThread(new Runnable() { @Override public void run() { if (!isError) { isError = true; disconnectWithErrorMessage(description); } } }); } // -----Implementation of AppRTCClient.AppRTCSignalingEvents --------------- // All callbacks are invoked from websocket signaling looper thread and // are routed to UI thread. private void onConnectedToRoomInternal(final SignalingParameters params) { final long delta = System.currentTimeMillis() - callStartedTimeMs; signalingParameters = params; logAndToast("Creating peer connection, delay=" + delta + "ms"); peerConnectionClient.createPeerConnection(rootEglBase.getEglBaseContext(), localRender, remoteRender, signalingParameters); if (signalingParameters.initiator) { logAndToast("Creating OFFER..."); // Create offer. Offer SDP will be sent to answering client in // PeerConnectionEvents.onLocalDescription event. peerConnectionClient.createOffer(); } else { if (params.offerSdp != null) { peerConnectionClient.setRemoteDescription(params.offerSdp); logAndToast("Creating ANSWER..."); // Create answer. Answer SDP will be sent to offering client in // PeerConnectionEvents.onLocalDescription event. peerConnectionClient.createAnswer(); } if (params.iceCandidates != null) { // Add remote ICE candidates from room. for (IceCandidate iceCandidate : params.iceCandidates) { peerConnectionClient.addRemoteIceCandidate(iceCandidate); } } } } @Override public void onConnectedToRoom(final SignalingParameters params) { runOnUiThread(new Runnable() { @Override public void run() { onConnectedToRoomInternal(params); } }); } @Override public void onRemoteDescription(final SessionDescription sdp) { final long delta = System.currentTimeMillis() - callStartedTimeMs; runOnUiThread(new Runnable() { @Override public void run() { if (peerConnectionClient == null) { Log.e(TAG, "Received remote SDP for non-initilized peer connection."); return; } logAndToast("Received remote " + sdp.type + ", delay=" + delta + "ms"); peerConnectionClient.setRemoteDescription(sdp); if (!signalingParameters.initiator) { logAndToast("Creating ANSWER..."); // Create answer. Answer SDP will be sent to offering client in // PeerConnectionEvents.onLocalDescription event. peerConnectionClient.createAnswer(); } } }); } @Override public void onRemoteIceCandidate(final IceCandidate candidate) { runOnUiThread(new Runnable() { @Override public void run() { if (peerConnectionClient == null) { Log.e(TAG, "Received ICE candidate for a non-initialized peer connection."); return; } peerConnectionClient.addRemoteIceCandidate(candidate); } }); } @Override public void onRemoteIceCandidatesRemoved(final IceCandidate[] candidates) { runOnUiThread(new Runnable() { @Override public void run() { if (peerConnectionClient == null) { Log.e(TAG, "Received ICE candidate removals for a non-initialized peer connection."); return; } peerConnectionClient.removeRemoteIceCandidates(candidates); } }); } @Override public void onChannelClose() { runOnUiThread(new Runnable() { @Override public void run() { logAndToast("Remote end hung up; dropping PeerConnection"); disconnect(); } }); } @Override public void onChannelError(final String description) { reportError(description); } // -----Implementation of PeerConnectionClient.PeerConnectionEvents.--------- // Send local peer connection SDP and ICE candidates to remote party. // All callbacks are invoked from peer connection client looper thread and // are routed to UI thread. @Override public void onLocalDescription(final SessionDescription sdp) { final long delta = System.currentTimeMillis() - callStartedTimeMs; runOnUiThread(new Runnable() { @Override public void run() { if (appRtcClient != null) { logAndToast("Sending " + sdp.type + ", delay=" + delta + "ms"); if (signalingParameters.initiator) { appRtcClient.sendOfferSdp(sdp); } else { appRtcClient.sendAnswerSdp(sdp); } } } }); } @Override public void onIceCandidate(final IceCandidate candidate) { runOnUiThread(new Runnable() { @Override public void run() { if (appRtcClient != null) { appRtcClient.sendLocalIceCandidate(candidate); } } }); } @Override public void onIceCandidatesRemoved(final IceCandidate[] candidates) { runOnUiThread(new Runnable() { @Override public void run() { if (appRtcClient != null) { appRtcClient.sendLocalIceCandidateRemovals(candidates); } } }); } @Override public void onIceConnected() { final long delta = System.currentTimeMillis() - callStartedTimeMs; runOnUiThread(new Runnable() { @Override public void run() { logAndToast("ICE connected, delay=" + delta + "ms"); iceConnected = true; callConnected(); } }); } @Override public void onIceDisconnected() { runOnUiThread(new Runnable() { @Override public void run() { logAndToast("ICE disconnected"); iceConnected = false; disconnect(); } }); } @Override public void onPeerConnectionClosed() { } @Override public void onPeerConnectionStatsReady(final StatsReport[] reports) { runOnUiThread(new Runnable() { @Override public void run() { if (!isError && iceConnected) { hudFragment.updateEncoderStatistics(reports); } } }); } @Override public void onPeerConnectionError(final String description) { reportError(description); } }
golden1232004/webrtc_new
webrtc/examples/androidapp/src/org/appspot/apprtc/CallActivity.java
Java
gpl-3.0
23,905
#undef ENABLE_NLS #undef HAVE_CATGETS #undef HAVE_GETTEXT #undef HAVE_LC_MESSAGES #undef HAVE_STPCPY #undef PACKAGE #undef VERSION
chimari/hoe
acconfig.h
C
gpl-3.0
131
########################################################################### # # This file is partially auto-generated by the DateTime::Locale generator # tools (v0.10). This code generator comes with the DateTime::Locale # distribution in the tools/ directory, and is called generate-modules. # # This file was generated from the CLDR JSON locale data. See the LICENSE.cldr # file included in this distribution for license details. # # Do not edit this file directly unless you are sure the part you are editing # is not created by the generator. # ########################################################################### =pod =encoding UTF-8 =head1 NAME DateTime::Locale::twq_NE - Locale data examples for the Tasawaq Niger (twq-NE) locale =head1 DESCRIPTION This pod file contains examples of the locale data available for the Tasawaq Niger locale. =head2 Days =head3 Wide (format) Atinni Atalaata Alarba Alhamiisa Alzuma Asibti Alhadi =head3 Abbreviated (format) Ati Ata Ala Alm Alz Asi Alh =head3 Narrow (format) T T L L L S H =head3 Wide (stand-alone) Atinni Atalaata Alarba Alhamiisa Alzuma Asibti Alhadi =head3 Abbreviated (stand-alone) Ati Ata Ala Alm Alz Asi Alh =head3 Narrow (stand-alone) T T L L L S H =head2 Months =head3 Wide (format) Žanwiye Feewiriye Marsi Awiril Me Žuweŋ Žuyye Ut Sektanbur Oktoobur Noowanbur Deesanbur =head3 Abbreviated (format) Žan Fee Mar Awi Me Žuw Žuy Ut Sek Okt Noo Dee =head3 Narrow (format) Ž F M A M Ž Ž U S O N D =head3 Wide (stand-alone) Žanwiye Feewiriye Marsi Awiril Me Žuweŋ Žuyye Ut Sektanbur Oktoobur Noowanbur Deesanbur =head3 Abbreviated (stand-alone) Žan Fee Mar Awi Me Žuw Žuy Ut Sek Okt Noo Dee =head3 Narrow (stand-alone) Ž F M A M Ž Ž U S O N D =head2 Quarters =head3 Wide (format) Arrubu 1 Arrubu 2 Arrubu 3 Arrubu 4 =head3 Abbreviated (format) A1 A2 A3 A4 =head3 Narrow (format) 1 2 3 4 =head3 Wide (stand-alone) Arrubu 1 Arrubu 2 Arrubu 3 Arrubu 4 =head3 Abbreviated (stand-alone) A1 A2 A3 A4 =head3 Narrow (stand-alone) 1 2 3 4 =head2 Eras =head3 Wide (format) Isaa jine Isaa zamanoo =head3 Abbreviated (format) IJ IZ =head3 Narrow (format) IJ IZ =head2 Date Formats =head3 Full 2008-02-05T18:30:30 = Atalaata 5 Feewiriye 2008 1995-12-22T09:05:02 = Alzuma 22 Deesanbur 1995 -0010-09-15T04:44:23 = Asibti 15 Sektanbur -10 =head3 Long 2008-02-05T18:30:30 = 5 Feewiriye 2008 1995-12-22T09:05:02 = 22 Deesanbur 1995 -0010-09-15T04:44:23 = 15 Sektanbur -10 =head3 Medium 2008-02-05T18:30:30 = 5 Fee 2008 1995-12-22T09:05:02 = 22 Dee 1995 -0010-09-15T04:44:23 = 15 Sek -10 =head3 Short 2008-02-05T18:30:30 = 5/2/2008 1995-12-22T09:05:02 = 22/12/1995 -0010-09-15T04:44:23 = 15/9/-10 =head2 Time Formats =head3 Full 2008-02-05T18:30:30 = 18:30:30 UTC 1995-12-22T09:05:02 = 09:05:02 UTC -0010-09-15T04:44:23 = 04:44:23 UTC =head3 Long 2008-02-05T18:30:30 = 18:30:30 UTC 1995-12-22T09:05:02 = 09:05:02 UTC -0010-09-15T04:44:23 = 04:44:23 UTC =head3 Medium 2008-02-05T18:30:30 = 18:30:30 1995-12-22T09:05:02 = 09:05:02 -0010-09-15T04:44:23 = 04:44:23 =head3 Short 2008-02-05T18:30:30 = 18:30 1995-12-22T09:05:02 = 09:05 -0010-09-15T04:44:23 = 04:44 =head2 Datetime Formats =head3 Full 2008-02-05T18:30:30 = Atalaata 5 Feewiriye 2008 18:30:30 UTC 1995-12-22T09:05:02 = Alzuma 22 Deesanbur 1995 09:05:02 UTC -0010-09-15T04:44:23 = Asibti 15 Sektanbur -10 04:44:23 UTC =head3 Long 2008-02-05T18:30:30 = 5 Feewiriye 2008 18:30:30 UTC 1995-12-22T09:05:02 = 22 Deesanbur 1995 09:05:02 UTC -0010-09-15T04:44:23 = 15 Sektanbur -10 04:44:23 UTC =head3 Medium 2008-02-05T18:30:30 = 5 Fee 2008 18:30:30 1995-12-22T09:05:02 = 22 Dee 1995 09:05:02 -0010-09-15T04:44:23 = 15 Sek -10 04:44:23 =head3 Short 2008-02-05T18:30:30 = 5/2/2008 18:30 1995-12-22T09:05:02 = 22/12/1995 09:05 -0010-09-15T04:44:23 = 15/9/-10 04:44 =head2 Available Formats =head3 Bh (h B) 2008-02-05T18:30:30 = 6 B 1995-12-22T09:05:02 = 9 B -0010-09-15T04:44:23 = 4 B =head3 Bhm (h:mm B) 2008-02-05T18:30:30 = 6:30 B 1995-12-22T09:05:02 = 9:05 B -0010-09-15T04:44:23 = 4:44 B =head3 Bhms (h:mm:ss B) 2008-02-05T18:30:30 = 6:30:30 B 1995-12-22T09:05:02 = 9:05:02 B -0010-09-15T04:44:23 = 4:44:23 B =head3 E (ccc) 2008-02-05T18:30:30 = Ata 1995-12-22T09:05:02 = Alz -0010-09-15T04:44:23 = Asi =head3 EBhm (E h:mm B) 2008-02-05T18:30:30 = Ata 6:30 B 1995-12-22T09:05:02 = Alz 9:05 B -0010-09-15T04:44:23 = Asi 4:44 B =head3 EBhms (E h:mm:ss B) 2008-02-05T18:30:30 = Ata 6:30:30 B 1995-12-22T09:05:02 = Alz 9:05:02 B -0010-09-15T04:44:23 = Asi 4:44:23 B =head3 EHm (E HH:mm) 2008-02-05T18:30:30 = Ata 18:30 1995-12-22T09:05:02 = Alz 09:05 -0010-09-15T04:44:23 = Asi 04:44 =head3 EHms (E HH:mm:ss) 2008-02-05T18:30:30 = Ata 18:30:30 1995-12-22T09:05:02 = Alz 09:05:02 -0010-09-15T04:44:23 = Asi 04:44:23 =head3 Ed (E d) 2008-02-05T18:30:30 = Ata 5 1995-12-22T09:05:02 = Alz 22 -0010-09-15T04:44:23 = Asi 15 =head3 Ehm (E h:mm a) 2008-02-05T18:30:30 = Ata 6:30 Zaarikay b 1995-12-22T09:05:02 = Alz 9:05 Subbaahi -0010-09-15T04:44:23 = Asi 4:44 Subbaahi =head3 Ehms (E h:mm:ss a) 2008-02-05T18:30:30 = Ata 6:30:30 Zaarikay b 1995-12-22T09:05:02 = Alz 9:05:02 Subbaahi -0010-09-15T04:44:23 = Asi 4:44:23 Subbaahi =head3 Gy (G y) 2008-02-05T18:30:30 = IZ 2008 1995-12-22T09:05:02 = IZ 1995 -0010-09-15T04:44:23 = IJ -10 =head3 GyMMM (G y MMM) 2008-02-05T18:30:30 = IZ 2008 Fee 1995-12-22T09:05:02 = IZ 1995 Dee -0010-09-15T04:44:23 = IJ -10 Sek =head3 GyMMMEd (G y MMM d, E) 2008-02-05T18:30:30 = IZ 2008 Fee 5, Ata 1995-12-22T09:05:02 = IZ 1995 Dee 22, Alz -0010-09-15T04:44:23 = IJ -10 Sek 15, Asi =head3 GyMMMd (G y MMM d) 2008-02-05T18:30:30 = IZ 2008 Fee 5 1995-12-22T09:05:02 = IZ 1995 Dee 22 -0010-09-15T04:44:23 = IJ -10 Sek 15 =head3 H (HH) 2008-02-05T18:30:30 = 18 1995-12-22T09:05:02 = 09 -0010-09-15T04:44:23 = 04 =head3 Hm (HH:mm) 2008-02-05T18:30:30 = 18:30 1995-12-22T09:05:02 = 09:05 -0010-09-15T04:44:23 = 04:44 =head3 Hms (HH:mm:ss) 2008-02-05T18:30:30 = 18:30:30 1995-12-22T09:05:02 = 09:05:02 -0010-09-15T04:44:23 = 04:44:23 =head3 Hmsv (HH:mm:ss v) 2008-02-05T18:30:30 = 18:30:30 UTC 1995-12-22T09:05:02 = 09:05:02 UTC -0010-09-15T04:44:23 = 04:44:23 UTC =head3 Hmv (HH:mm v) 2008-02-05T18:30:30 = 18:30 UTC 1995-12-22T09:05:02 = 09:05 UTC -0010-09-15T04:44:23 = 04:44 UTC =head3 M (L) 2008-02-05T18:30:30 = 2 1995-12-22T09:05:02 = 12 -0010-09-15T04:44:23 = 9 =head3 MEd (E d/M) 2008-02-05T18:30:30 = Ata 5/2 1995-12-22T09:05:02 = Alz 22/12 -0010-09-15T04:44:23 = Asi 15/9 =head3 MMM (LLL) 2008-02-05T18:30:30 = Fee 1995-12-22T09:05:02 = Dee -0010-09-15T04:44:23 = Sek =head3 MMMEd (E d MMM) 2008-02-05T18:30:30 = Ata 5 Fee 1995-12-22T09:05:02 = Alz 22 Dee -0010-09-15T04:44:23 = Asi 15 Sek =head3 MMMMW-count-other ('week' W 'of' MMMM) 2008-02-05T18:30:30 = week 1 of Feewiriye 1995-12-22T09:05:02 = week 3 of Deesanbur -0010-09-15T04:44:23 = week 2 of Sektanbur =head3 MMMMd (MMMM d) 2008-02-05T18:30:30 = Feewiriye 5 1995-12-22T09:05:02 = Deesanbur 22 -0010-09-15T04:44:23 = Sektanbur 15 =head3 MMMd (d MMM) 2008-02-05T18:30:30 = 5 Fee 1995-12-22T09:05:02 = 22 Dee -0010-09-15T04:44:23 = 15 Sek =head3 Md (d/M) 2008-02-05T18:30:30 = 5/2 1995-12-22T09:05:02 = 22/12 -0010-09-15T04:44:23 = 15/9 =head3 d (d) 2008-02-05T18:30:30 = 5 1995-12-22T09:05:02 = 22 -0010-09-15T04:44:23 = 15 =head3 h (h a) 2008-02-05T18:30:30 = 6 Zaarikay b 1995-12-22T09:05:02 = 9 Subbaahi -0010-09-15T04:44:23 = 4 Subbaahi =head3 hm (h:mm a) 2008-02-05T18:30:30 = 6:30 Zaarikay b 1995-12-22T09:05:02 = 9:05 Subbaahi -0010-09-15T04:44:23 = 4:44 Subbaahi =head3 hms (h:mm:ss a) 2008-02-05T18:30:30 = 6:30:30 Zaarikay b 1995-12-22T09:05:02 = 9:05:02 Subbaahi -0010-09-15T04:44:23 = 4:44:23 Subbaahi =head3 hmsv (h:mm:ss a v) 2008-02-05T18:30:30 = 6:30:30 Zaarikay b UTC 1995-12-22T09:05:02 = 9:05:02 Subbaahi UTC -0010-09-15T04:44:23 = 4:44:23 Subbaahi UTC =head3 hmv (h:mm a v) 2008-02-05T18:30:30 = 6:30 Zaarikay b UTC 1995-12-22T09:05:02 = 9:05 Subbaahi UTC -0010-09-15T04:44:23 = 4:44 Subbaahi UTC =head3 ms (m:ss) 2008-02-05T18:30:30 = 30:30 1995-12-22T09:05:02 = 5:02 -0010-09-15T04:44:23 = 44:23 =head3 y (y) 2008-02-05T18:30:30 = 2008 1995-12-22T09:05:02 = 1995 -0010-09-15T04:44:23 = -10 =head3 yM (M/y) 2008-02-05T18:30:30 = 2/2008 1995-12-22T09:05:02 = 12/1995 -0010-09-15T04:44:23 = 9/-10 =head3 yMEd (E d/M/y) 2008-02-05T18:30:30 = Ata 5/2/2008 1995-12-22T09:05:02 = Alz 22/12/1995 -0010-09-15T04:44:23 = Asi 15/9/-10 =head3 yMMM (MMM y) 2008-02-05T18:30:30 = Fee 2008 1995-12-22T09:05:02 = Dee 1995 -0010-09-15T04:44:23 = Sek -10 =head3 yMMMEd (E d MMM y) 2008-02-05T18:30:30 = Ata 5 Fee 2008 1995-12-22T09:05:02 = Alz 22 Dee 1995 -0010-09-15T04:44:23 = Asi 15 Sek -10 =head3 yMMMM (y MMMM) 2008-02-05T18:30:30 = 2008 Feewiriye 1995-12-22T09:05:02 = 1995 Deesanbur -0010-09-15T04:44:23 = -10 Sektanbur =head3 yMMMd (d MMM y) 2008-02-05T18:30:30 = 5 Fee 2008 1995-12-22T09:05:02 = 22 Dee 1995 -0010-09-15T04:44:23 = 15 Sek -10 =head3 yMd (d/M/y) 2008-02-05T18:30:30 = 5/2/2008 1995-12-22T09:05:02 = 22/12/1995 -0010-09-15T04:44:23 = 15/9/-10 =head3 yQQQ (QQQ y) 2008-02-05T18:30:30 = A1 2008 1995-12-22T09:05:02 = A4 1995 -0010-09-15T04:44:23 = A3 -10 =head3 yQQQQ (QQQQ y) 2008-02-05T18:30:30 = Arrubu 1 2008 1995-12-22T09:05:02 = Arrubu 4 1995 -0010-09-15T04:44:23 = Arrubu 3 -10 =head3 yw-count-other ('week' w 'of' Y) 2008-02-05T18:30:30 = week 6 of 2008 1995-12-22T09:05:02 = week 51 of 1995 -0010-09-15T04:44:23 = week 37 of -10 =head2 Miscellaneous =head3 Prefers 24 hour time? Yes =head3 Local first day of the week 1 (Atinni) =head1 SUPPORT See L<DateTime::Locale>. =cut
kiamazi/mira
local/lib/perl5/DateTime/Locale/twq_NE.pod
Perl
gpl-3.0
10,451
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_PROPERTY_H_ #define V8_PROPERTY_H_ #include "isolate.h" #include "factory.h" #include "types.h" namespace v8 { namespace internal { // Abstraction for elements in instance-descriptor arrays. // // Each descriptor has a key, property attributes, property type, // property index (in the actual instance-descriptor array) and // optionally a piece of data. class Descriptor BASE_EMBEDDED { public: void KeyToUniqueName() { if (!key_->IsUniqueName()) { key_ = key_->GetIsolate()->factory()->InternalizeString( Handle<String>::cast(key_)); } } Handle<Name> GetKey() { return key_; } Handle<Object> GetValue() { return value_; } PropertyDetails GetDetails() { return details_; } #ifdef OBJECT_PRINT void Print(FILE* out); #endif void SetSortedKeyIndex(int index) { details_ = details_.set_pointer(index); } private: Handle<Name> key_; Handle<Object> value_; PropertyDetails details_; protected: Descriptor() : details_(Smi::FromInt(0)) {} void Init(Handle<Name> key, Handle<Object> value, PropertyDetails details) { key_ = key; value_ = value; details_ = details; } Descriptor(Handle<Name> key, Handle<Object> value, PropertyDetails details) : key_(key), value_(value), details_(details) { } Descriptor(Handle<Name> key, Handle<Object> value, PropertyAttributes attributes, PropertyType type, Representation representation, int field_index = 0) : key_(key), value_(value), details_(attributes, type, representation, field_index) { } friend class DescriptorArray; friend class Map; }; class FieldDescriptor V8_FINAL : public Descriptor { public: FieldDescriptor(Handle<Name> key, int field_index, PropertyAttributes attributes, Representation representation) : Descriptor(key, HeapType::Any(key->GetIsolate()), attributes, FIELD, representation, field_index) {} FieldDescriptor(Handle<Name> key, int field_index, Handle<HeapType> field_type, PropertyAttributes attributes, Representation representation) : Descriptor(key, field_type, attributes, FIELD, representation, field_index) { } }; class ConstantDescriptor V8_FINAL : public Descriptor { public: ConstantDescriptor(Handle<Name> key, Handle<Object> value, PropertyAttributes attributes) : Descriptor(key, value, attributes, CONSTANT, value->OptimalRepresentation()) {} }; class CallbacksDescriptor V8_FINAL : public Descriptor { public: CallbacksDescriptor(Handle<Name> key, Handle<Object> foreign, PropertyAttributes attributes) : Descriptor(key, foreign, attributes, CALLBACKS, Representation::Tagged()) {} }; // Holds a property index value distinguishing if it is a field index or an // index inside the object header. class PropertyIndex V8_FINAL { public: static PropertyIndex NewFieldIndex(int index) { return PropertyIndex(index, false); } static PropertyIndex NewHeaderIndex(int index) { return PropertyIndex(index, true); } bool is_field_index() { return (index_ & kHeaderIndexBit) == 0; } bool is_header_index() { return (index_ & kHeaderIndexBit) != 0; } int field_index() { ASSERT(is_field_index()); return value(); } int header_index() { ASSERT(is_header_index()); return value(); } bool is_inobject(Handle<JSObject> holder) { if (is_header_index()) return true; return field_index() < holder->map()->inobject_properties(); } int translate(Handle<JSObject> holder) { if (is_header_index()) return header_index(); int index = field_index() - holder->map()->inobject_properties(); if (index >= 0) return index; return index + holder->map()->instance_size() / kPointerSize; } private: static const int kHeaderIndexBit = 1 << 31; static const int kIndexMask = ~kHeaderIndexBit; int value() { return index_ & kIndexMask; } PropertyIndex(int index, bool is_header_based) : index_(index | (is_header_based ? kHeaderIndexBit : 0)) { ASSERT(index <= kIndexMask); } int index_; }; class LookupResult V8_FINAL BASE_EMBEDDED { public: explicit LookupResult(Isolate* isolate) : isolate_(isolate), next_(isolate->top_lookup_result()), lookup_type_(NOT_FOUND), holder_(NULL), transition_(NULL), cacheable_(true), details_(NONE, NONEXISTENT, Representation::None()) { isolate->set_top_lookup_result(this); } ~LookupResult() { ASSERT(isolate()->top_lookup_result() == this); isolate()->set_top_lookup_result(next_); } Isolate* isolate() const { return isolate_; } void DescriptorResult(JSObject* holder, PropertyDetails details, int number) { lookup_type_ = DESCRIPTOR_TYPE; holder_ = holder; transition_ = NULL; details_ = details; number_ = number; } bool CanHoldValue(Handle<Object> value) const { switch (type()) { case NORMAL: return true; case FIELD: return value->FitsRepresentation(representation()) && GetFieldType()->NowContains(value); case CONSTANT: ASSERT(GetConstant() != *value || value->FitsRepresentation(representation())); return GetConstant() == *value; case CALLBACKS: case HANDLER: case INTERCEPTOR: return true; case NONEXISTENT: UNREACHABLE(); } UNREACHABLE(); return true; } void TransitionResult(JSObject* holder, Map* target) { lookup_type_ = TRANSITION_TYPE; number_ = target->LastAdded(); details_ = target->instance_descriptors()->GetDetails(number_); holder_ = holder; transition_ = target; } void DictionaryResult(JSObject* holder, int entry) { lookup_type_ = DICTIONARY_TYPE; holder_ = holder; transition_ = NULL; details_ = holder->property_dictionary()->DetailsAt(entry); number_ = entry; } void HandlerResult(JSProxy* proxy) { lookup_type_ = HANDLER_TYPE; holder_ = proxy; transition_ = NULL; details_ = PropertyDetails(NONE, HANDLER, Representation::Tagged()); cacheable_ = false; } void InterceptorResult(JSObject* holder) { lookup_type_ = INTERCEPTOR_TYPE; holder_ = holder; transition_ = NULL; details_ = PropertyDetails(NONE, INTERCEPTOR, Representation::Tagged()); } void NotFound() { lookup_type_ = NOT_FOUND; details_ = PropertyDetails(NONE, NONEXISTENT, Representation::None()); holder_ = NULL; transition_ = NULL; } JSObject* holder() const { ASSERT(IsFound()); return JSObject::cast(holder_); } JSProxy* proxy() const { ASSERT(IsHandler()); return JSProxy::cast(holder_); } PropertyType type() const { ASSERT(IsFound()); return details_.type(); } Representation representation() const { ASSERT(IsFound()); ASSERT(details_.type() != NONEXISTENT); return details_.representation(); } PropertyAttributes GetAttributes() const { ASSERT(IsFound()); ASSERT(details_.type() != NONEXISTENT); return details_.attributes(); } PropertyDetails GetPropertyDetails() const { return details_; } bool IsFastPropertyType() const { ASSERT(IsFound()); return IsTransition() || type() != NORMAL; } // Property callbacks does not include transitions to callbacks. bool IsPropertyCallbacks() const { ASSERT(!(details_.type() == CALLBACKS && !IsFound())); return !IsTransition() && details_.type() == CALLBACKS; } bool IsReadOnly() const { ASSERT(IsFound()); ASSERT(details_.type() != NONEXISTENT); return details_.IsReadOnly(); } bool IsField() const { ASSERT(!(details_.type() == FIELD && !IsFound())); return IsDescriptorOrDictionary() && type() == FIELD; } bool IsNormal() const { ASSERT(!(details_.type() == NORMAL && !IsFound())); return IsDescriptorOrDictionary() && type() == NORMAL; } bool IsConstant() const { ASSERT(!(details_.type() == CONSTANT && !IsFound())); return IsDescriptorOrDictionary() && type() == CONSTANT; } bool IsConstantFunction() const { return IsConstant() && GetConstant()->IsJSFunction(); } bool IsDontDelete() const { return details_.IsDontDelete(); } bool IsDontEnum() const { return details_.IsDontEnum(); } bool IsFound() const { return lookup_type_ != NOT_FOUND; } bool IsDescriptorOrDictionary() const { return lookup_type_ == DESCRIPTOR_TYPE || lookup_type_ == DICTIONARY_TYPE; } bool IsTransition() const { return lookup_type_ == TRANSITION_TYPE; } bool IsHandler() const { return lookup_type_ == HANDLER_TYPE; } bool IsInterceptor() const { return lookup_type_ == INTERCEPTOR_TYPE; } // Is the result is a property excluding transitions and the null descriptor? bool IsProperty() const { return IsFound() && !IsTransition(); } bool IsDataProperty() const { switch (lookup_type_) { case NOT_FOUND: case TRANSITION_TYPE: case HANDLER_TYPE: case INTERCEPTOR_TYPE: return false; case DESCRIPTOR_TYPE: case DICTIONARY_TYPE: switch (type()) { case FIELD: case NORMAL: case CONSTANT: return true; case CALLBACKS: { Object* callback = GetCallbackObject(); ASSERT(!callback->IsForeign()); return callback->IsAccessorInfo(); } case HANDLER: case INTERCEPTOR: case NONEXISTENT: UNREACHABLE(); return false; } } UNREACHABLE(); return false; } bool IsCacheable() const { return cacheable_; } void DisallowCaching() { cacheable_ = false; } Object* GetLazyValue() const { switch (lookup_type_) { case NOT_FOUND: case TRANSITION_TYPE: case HANDLER_TYPE: case INTERCEPTOR_TYPE: return isolate()->heap()->the_hole_value(); case DESCRIPTOR_TYPE: case DICTIONARY_TYPE: switch (type()) { case FIELD: return holder()->RawFastPropertyAt(GetFieldIndex().field_index()); case NORMAL: { Object* value = holder()->property_dictionary()->ValueAt( GetDictionaryEntry()); if (holder()->IsGlobalObject()) { value = PropertyCell::cast(value)->value(); } return value; } case CONSTANT: return GetConstant(); case CALLBACKS: return isolate()->heap()->the_hole_value(); case HANDLER: case INTERCEPTOR: case NONEXISTENT: UNREACHABLE(); return NULL; } } UNREACHABLE(); return NULL; } Map* GetTransitionTarget() const { ASSERT(IsTransition()); return transition_; } bool IsTransitionToField() const { return IsTransition() && details_.type() == FIELD; } bool IsTransitionToConstant() const { return IsTransition() && details_.type() == CONSTANT; } int GetDescriptorIndex() const { ASSERT(lookup_type_ == DESCRIPTOR_TYPE); return number_; } PropertyIndex GetFieldIndex() const { ASSERT(lookup_type_ == DESCRIPTOR_TYPE || lookup_type_ == TRANSITION_TYPE); return PropertyIndex::NewFieldIndex(GetFieldIndexFromMap(holder()->map())); } int GetLocalFieldIndexFromMap(Map* map) const { return GetFieldIndexFromMap(map) - map->inobject_properties(); } int GetDictionaryEntry() const { ASSERT(lookup_type_ == DICTIONARY_TYPE); return number_; } JSFunction* GetConstantFunction() const { ASSERT(type() == CONSTANT); return JSFunction::cast(GetValue()); } Object* GetConstantFromMap(Map* map) const { ASSERT(type() == CONSTANT); return GetValueFromMap(map); } JSFunction* GetConstantFunctionFromMap(Map* map) const { return JSFunction::cast(GetConstantFromMap(map)); } Object* GetConstant() const { ASSERT(type() == CONSTANT); return GetValue(); } Object* GetCallbackObject() const { ASSERT(!IsTransition()); ASSERT(type() == CALLBACKS); return GetValue(); } #ifdef OBJECT_PRINT void Print(FILE* out); #endif Object* GetValue() const { if (lookup_type_ == DESCRIPTOR_TYPE) { return GetValueFromMap(holder()->map()); } else if (lookup_type_ == TRANSITION_TYPE) { return GetValueFromMap(transition_); } // In the dictionary case, the data is held in the value field. ASSERT(lookup_type_ == DICTIONARY_TYPE); return holder()->GetNormalizedProperty(this); } Object* GetValueFromMap(Map* map) const { ASSERT(lookup_type_ == DESCRIPTOR_TYPE || lookup_type_ == TRANSITION_TYPE); ASSERT(number_ < map->NumberOfOwnDescriptors()); return map->instance_descriptors()->GetValue(number_); } int GetFieldIndexFromMap(Map* map) const { ASSERT(lookup_type_ == DESCRIPTOR_TYPE || lookup_type_ == TRANSITION_TYPE); ASSERT(number_ < map->NumberOfOwnDescriptors()); return map->instance_descriptors()->GetFieldIndex(number_); } HeapType* GetFieldType() const { ASSERT(type() == FIELD); if (lookup_type_ == DESCRIPTOR_TYPE) { return GetFieldTypeFromMap(holder()->map()); } ASSERT(lookup_type_ == TRANSITION_TYPE); return GetFieldTypeFromMap(transition_); } HeapType* GetFieldTypeFromMap(Map* map) const { ASSERT(lookup_type_ == DESCRIPTOR_TYPE || lookup_type_ == TRANSITION_TYPE); ASSERT(number_ < map->NumberOfOwnDescriptors()); return map->instance_descriptors()->GetFieldType(number_); } Map* GetFieldOwner() const { return GetFieldOwnerFromMap(holder()->map()); } Map* GetFieldOwnerFromMap(Map* map) const { ASSERT(lookup_type_ == DESCRIPTOR_TYPE || lookup_type_ == TRANSITION_TYPE); ASSERT(number_ < map->NumberOfOwnDescriptors()); return map->FindFieldOwner(number_); } void Iterate(ObjectVisitor* visitor); private: Isolate* isolate_; LookupResult* next_; // Where did we find the result; enum { NOT_FOUND, DESCRIPTOR_TYPE, TRANSITION_TYPE, DICTIONARY_TYPE, HANDLER_TYPE, INTERCEPTOR_TYPE } lookup_type_; JSReceiver* holder_; Map* transition_; int number_; bool cacheable_; PropertyDetails details_; }; } } // namespace v8::internal #endif // V8_PROPERTY_H_
jiachenning/fibjs
vender/src/v8/src/property.h
C
gpl-3.0
14,833
# -*- coding: utf-8 -*- import json from catmaid.models import Message from .common import CatmaidApiTestCase class MessagesApiTests(CatmaidApiTestCase): def test_read_message_error(self): self.fake_authentication() message_id = 5050 response = self.client.post(f'/messages/{message_id}/mark_read') self.assertEqual(response.status_code, 404) parsed_response = json.loads(response.content.decode('utf-8')) self.assertIn('error', parsed_response) self.assertIn('type', parsed_response) self.assertEquals('Http404', parsed_response['type']) def test_read_message_without_action(self): self.fake_authentication() message_id = 3 response = self.client.post(f'/messages/{message_id}/mark_read') self.assertStatus(response) parsed_response = json.loads(response.content.decode('utf-8')) message = Message.objects.get(id=message_id) self.assertEqual(True, message.read) self.assertTrue(parsed_response.get('success')) def test_read_message_with_action(self): self.fake_authentication() message_id = 1 response = self.client.post(f'/messages/{message_id}/mark_read') self.assertEqual(response.status_code, 302) message = Message.objects.filter(id=message_id)[0] self.assertEqual(True, message.read) def test_list_messages(self): self.fake_authentication() response = self.client.post( '/messages/list', {}) self.assertStatus(response) parsed_response = json.loads(response.content.decode('utf-8')) def get_message(data, id): msgs = [d for d in data if d['id'] == id] if len(msgs) != 1: raise ValueError("Malformed message data") return msgs[0] expected_result = { '0': { 'action': '', 'id': 3, 'text': 'Contents of message 3.', 'time': '2014-10-05 11:12:01.360422+00:00', 'title': 'Message 3' }, '1': { 'action': 'http://www.example.com/message2', 'id': 2, 'text': 'Contents of message 2.', 'time': '2011-12-20 16:46:01.360422+00:00', 'title': 'Message 2' }, '2': { 'action': 'http://www.example.com/message1', 'id': 1, 'text': 'Contents of message 1.', 'time': '2011-12-19 16:46:01+00:00', 'title': 'Message 1' }, '3': { 'id': -1, 'notification_count': 0 } } # Check result independent from order for mi in ('0','1','2','3'): self.assertEqual(expected_result[mi], parsed_response[mi])
catmaid/CATMAID
django/applications/catmaid/tests/apis/test_messages.py
Python
gpl-3.0
3,008
/** * Copyright (C) 2008 Happy Fish / YuQing * * FastDFS may be copied only under the terms of the GNU General * Public License V3, which may be found in the FastDFS source kit. * Please visit the FastDFS Home Page http://www.csource.org/ for more detail. **/ #ifndef _FDFS_HTTP_SHARED_H #define _FDFS_HTTP_SHARED_H #include <time.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "ini_file_reader.h" #include "hash.h" typedef struct { bool disabled; bool anti_steal_token; /* if need find content type by file extension name */ bool need_find_content_type; /* the web server port */ int server_port; /* key is file ext name, value is content type */ HashArray content_type_hash; BufferInfo anti_steal_secret_key; BufferInfo token_check_fail_buff; char default_content_type[64]; char token_check_fail_content_type[64]; int token_ttl; } FDFSHTTPParams; #ifdef __cplusplus extern "C" { #endif /** load HTTP params from conf file params: pIniContext: the ini file items, return by iniLoadItems conf_filename: config filename pHTTPParams: the HTTP params return: 0 for success, != 0 fail **/ int fdfs_http_params_load(IniContext *pIniContext, \ const char *conf_filename, FDFSHTTPParams *pHTTPParams); void fdfs_http_params_destroy(FDFSHTTPParams *pParams); /** generate anti-steal token params: secret_key: secret key buffer file_id: FastDFS file id timestamp: current timestamp, unix timestamp (seconds), 0 for never timeout token: return token buffer return: 0 for success, != 0 fail **/ int fdfs_http_gen_token(const BufferInfo *secret_key, const char *file_id, \ const int timestamp, char *token); /** check anti-steal token params: secret_key: secret key buffer file_id: FastDFS file id timestamp: the timestamp to generate the token, unix timestamp (seconds) token: token buffer ttl: token ttl, delta seconds return: 0 for passed, != 0 fail **/ int fdfs_http_check_token(const BufferInfo *secret_key, const char *file_id, \ const int timestamp, const char *token, const int ttl); /** get parameter value params: param_name: the parameter name to get params: parameter array param_count: param count return: param value pointer, return NULL if not exist **/ char *fdfs_http_get_parameter(const char *param_name, KeyValuePair *params, \ const int param_count); /** get file extension name params: filename: the filename filename_len: the length of filename ext_len: return the length of extension name return: extension name, NULL for none **/ const char *fdfs_http_get_file_extension(const char *filename, \ const int filename_len, int *ext_len); /** get content type by file extension name params: pHTTPParams: the HTTP params ext_name: the extension name ext_len: the length of extension name content_type: return content type content_type_size: content type buffer size return: 0 for success, != 0 fail **/ int fdfs_http_get_content_type_by_extname(FDFSHTTPParams *pParams, \ const char *ext_name, const int ext_len, \ char *content_type, const int content_type_size); #ifdef __cplusplus } #endif #endif
fatedier/studies
fastdfs-5.01/common/fdfs_http_shared.h
C
gpl-3.0
3,117
// DeflateDecoder.cpp #include "StdAfx.h" #include "DeflateDecoder.h" namespace NCompress { namespace NDeflate { namespace NDecoder { CCoder::CCoder(bool deflate64Mode): _deflate64Mode(deflate64Mode), _deflateNSIS(false), _keepHistory(false), _needFinishInput(false), _needInitInStream(true), _outSizeDefined(false), _outStartPos(0), ZlibMode(false) {} UInt32 CCoder::ReadBits(unsigned numBits) { return m_InBitStream.ReadBits(numBits); } Byte CCoder::ReadAlignedByte() { return m_InBitStream.ReadAlignedByte(); } bool CCoder::DecodeLevels(Byte *levels, unsigned numSymbols) { unsigned i = 0; do { UInt32 sym = m_LevelDecoder.Decode(&m_InBitStream); if (sym < kTableDirectLevels) levels[i++] = (Byte)sym; else { if (sym >= kLevelTableSize) return false; unsigned num; unsigned numBits; Byte symbol; if (sym == kTableLevelRepNumber) { if (i == 0) return false; numBits = 2; num = 0; symbol = levels[(size_t)i - 1]; } else { sym -= kTableLevel0Number; sym <<= 2; numBits = 3 + (unsigned)sym; num = ((unsigned)sym << 1); symbol = 0; } num += i + 3 + ReadBits(numBits); if (num > numSymbols) return false; do levels[i++] = symbol; while (i < num); } } while (i < numSymbols); return true; } #define RIF(x) { if (!(x)) return false; } bool CCoder::ReadTables(void) { m_FinalBlock = (ReadBits(kFinalBlockFieldSize) == NFinalBlockField::kFinalBlock); if (m_InBitStream.ExtraBitsWereRead()) return false; UInt32 blockType = ReadBits(kBlockTypeFieldSize); if (blockType > NBlockType::kDynamicHuffman) return false; if (m_InBitStream.ExtraBitsWereRead()) return false; if (blockType == NBlockType::kStored) { m_StoredMode = true; m_InBitStream.AlignToByte(); m_StoredBlockSize = ReadAligned_UInt16(); // ReadBits(kStoredBlockLengthFieldSize) if (_deflateNSIS) return true; return (m_StoredBlockSize == (UInt16)~ReadAligned_UInt16()); } m_StoredMode = false; CLevels levels; if (blockType == NBlockType::kFixedHuffman) { levels.SetFixedLevels(); _numDistLevels = _deflate64Mode ? kDistTableSize64 : kDistTableSize32; } else { unsigned numLitLenLevels = ReadBits(kNumLenCodesFieldSize) + kNumLitLenCodesMin; _numDistLevels = ReadBits(kNumDistCodesFieldSize) + kNumDistCodesMin; unsigned numLevelCodes = ReadBits(kNumLevelCodesFieldSize) + kNumLevelCodesMin; if (!_deflate64Mode) if (_numDistLevels > kDistTableSize32) return false; Byte levelLevels[kLevelTableSize]; for (unsigned i = 0; i < kLevelTableSize; i++) { unsigned position = kCodeLengthAlphabetOrder[i]; if (i < numLevelCodes) levelLevels[position] = (Byte)ReadBits(kLevelFieldSize); else levelLevels[position] = 0; } if (m_InBitStream.ExtraBitsWereRead()) return false; RIF(m_LevelDecoder.Build(levelLevels)); Byte tmpLevels[kFixedMainTableSize + kFixedDistTableSize]; if (!DecodeLevels(tmpLevels, numLitLenLevels + _numDistLevels)) return false; if (m_InBitStream.ExtraBitsWereRead()) return false; levels.SubClear(); memcpy(levels.litLenLevels, tmpLevels, numLitLenLevels); memcpy(levels.distLevels, tmpLevels + numLitLenLevels, _numDistLevels); } RIF(m_MainDecoder.Build(levels.litLenLevels)); return m_DistDecoder.Build(levels.distLevels); } HRESULT CCoder::InitInStream(bool needInit) { if (needInit) { // for HDD-Windows: // (1 << 15) - best for reading only prefetch // (1 << 22) - best for real reading / writing if (!m_InBitStream.Create(1 << 20)) return E_OUTOFMEMORY; m_InBitStream.Init(); _needInitInStream = false; } return S_OK; } HRESULT CCoder::CodeSpec(UInt32 curSize, bool finishInputStream, UInt32 inputProgressLimit) { if (_remainLen == kLenIdFinished) return S_OK; if (_remainLen == kLenIdNeedInit) { if (!_keepHistory) if (!m_OutWindowStream.Create(_deflate64Mode ? kHistorySize64: kHistorySize32)) return E_OUTOFMEMORY; RINOK(InitInStream(_needInitInStream)); m_OutWindowStream.Init(_keepHistory); m_FinalBlock = false; _remainLen = 0; _needReadTable = true; } while (_remainLen > 0 && curSize > 0) { _remainLen--; Byte b = m_OutWindowStream.GetByte(_rep0); m_OutWindowStream.PutByte(b); curSize--; } UInt64 inputStart = 0; if (inputProgressLimit != 0) inputStart = m_InBitStream.GetProcessedSize(); while (curSize > 0 || finishInputStream) { if (m_InBitStream.ExtraBitsWereRead()) return S_FALSE; if (_needReadTable) { if (m_FinalBlock) { _remainLen = kLenIdFinished; break; } if (inputProgressLimit != 0) if (m_InBitStream.GetProcessedSize() - inputStart >= inputProgressLimit) return S_OK; if (!ReadTables()) return S_FALSE; if (m_InBitStream.ExtraBitsWereRead()) return S_FALSE; _needReadTable = false; } if (m_StoredMode) { if (finishInputStream && curSize == 0 && m_StoredBlockSize != 0) return S_FALSE; /* NSIS version contains some bits in bitl bits buffer. So we must read some first bytes via ReadAlignedByte */ for (; m_StoredBlockSize > 0 && curSize > 0 && m_InBitStream.ThereAreDataInBitsBuffer(); m_StoredBlockSize--, curSize--) m_OutWindowStream.PutByte(ReadAlignedByte()); for (; m_StoredBlockSize > 0 && curSize > 0; m_StoredBlockSize--, curSize--) m_OutWindowStream.PutByte(m_InBitStream.ReadDirectByte()); _needReadTable = (m_StoredBlockSize == 0); continue; } while (curSize > 0) { if (m_InBitStream.ExtraBitsWereRead_Fast()) return S_FALSE; UInt32 sym = m_MainDecoder.Decode(&m_InBitStream); if (sym < 0x100) { m_OutWindowStream.PutByte((Byte)sym); curSize--; continue; } else if (sym == kSymbolEndOfBlock) { _needReadTable = true; break; } else if (sym < kMainTableSize) { sym -= kSymbolMatch; UInt32 len; { unsigned numBits; if (_deflate64Mode) { len = kLenStart64[sym]; numBits = kLenDirectBits64[sym]; } else { len = kLenStart32[sym]; numBits = kLenDirectBits32[sym]; } len += kMatchMinLen + m_InBitStream.ReadBits(numBits); } UInt32 locLen = len; if (locLen > curSize) locLen = (UInt32)curSize; sym = m_DistDecoder.Decode(&m_InBitStream); if (sym >= _numDistLevels) return S_FALSE; UInt32 distance = kDistStart[sym] + m_InBitStream.ReadBits(kDistDirectBits[sym]); if (!m_OutWindowStream.CopyBlock(distance, locLen)) return S_FALSE; curSize -= locLen; len -= locLen; if (len != 0) { _remainLen = (Int32)len; _rep0 = distance; break; } } else return S_FALSE; } if (finishInputStream && curSize == 0) { if (m_MainDecoder.Decode(&m_InBitStream) != kSymbolEndOfBlock) return S_FALSE; _needReadTable = true; } } if (m_InBitStream.ExtraBitsWereRead()) return S_FALSE; return S_OK; } #ifdef _NO_EXCEPTIONS #define DEFLATE_TRY_BEGIN #define DEFLATE_TRY_END(res) #else #define DEFLATE_TRY_BEGIN try { #define DEFLATE_TRY_END(res) } \ catch(const CSystemException &e) { res = e.ErrorCode; } \ catch(...) { res = S_FALSE; } // catch(const CInBufferException &e) { res = e.ErrorCode; } // catch(const CLzOutWindowException &e) { res = e.ErrorCode; } #endif HRESULT CCoder::CodeReal(ISequentialOutStream *outStream, ICompressProgressInfo *progress) { HRESULT res; DEFLATE_TRY_BEGIN m_OutWindowStream.SetStream(outStream); CCoderReleaser flusher(this); const UInt64 inStart = _needInitInStream ? 0 : m_InBitStream.GetProcessedSize(); for (;;) { const UInt32 kInputProgressLimit = 1 << 21; UInt32 curSize = 1 << 20; bool finishInputStream = false; if (_outSizeDefined) { const UInt64 rem = _outSize - GetOutProcessedCur(); if (curSize >= rem) { curSize = (UInt32)rem; if (ZlibMode || _needFinishInput) finishInputStream = true; } } if (!finishInputStream && curSize == 0) break; RINOK(CodeSpec(curSize, finishInputStream, progress ? kInputProgressLimit : 0)); if (_remainLen == kLenIdFinished) break; if (progress) { const UInt64 inSize = m_InBitStream.GetProcessedSize() - inStart; const UInt64 nowPos64 = GetOutProcessedCur(); RINOK(progress->SetRatioInfo(&inSize, &nowPos64)); } } if (_remainLen == kLenIdFinished && ZlibMode) { m_InBitStream.AlignToByte(); for (unsigned i = 0; i < 4; i++) ZlibFooter[i] = ReadAlignedByte(); } flusher.NeedFlush = false; res = Flush(); if (res == S_OK && _remainLen != kLenIdNeedInit && InputEofError()) return S_FALSE; DEFLATE_TRY_END(res) return res; } HRESULT CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress) { SetInStream(inStream); SetOutStreamSize(outSize); HRESULT res = CodeReal(outStream, progress); ReleaseInStream(); /* if (res == S_OK) if (_needFinishInput && inSize && *inSize != m_InBitStream.GetProcessedSize()) res = S_FALSE; */ return res; } STDMETHODIMP CCoder::SetFinishMode(UInt32 finishMode) { Set_NeedFinishInput(finishMode != 0); return S_OK; } STDMETHODIMP CCoder::GetInStreamProcessedSize(UInt64 *value) { if (!value) return E_INVALIDARG; *value = m_InBitStream.GetProcessedSize(); return S_OK; } STDMETHODIMP CCoder::SetInStream(ISequentialInStream *inStream) { m_InStreamRef = inStream; m_InBitStream.SetStream(inStream); return S_OK; } STDMETHODIMP CCoder::ReleaseInStream() { m_InStreamRef.Release(); return S_OK; } void CCoder::SetOutStreamSizeResume(const UInt64 *outSize) { _outSizeDefined = (outSize != NULL); _outSize = 0; if (_outSizeDefined) _outSize = *outSize; m_OutWindowStream.Init(_keepHistory); _outStartPos = m_OutWindowStream.GetProcessedSize(); _remainLen = kLenIdNeedInit; } STDMETHODIMP CCoder::SetOutStreamSize(const UInt64 *outSize) { /* 18.06: We want to support GetInputProcessedSize() before CCoder::Read() So we call m_InBitStream.Init() even before buffer allocations m_InBitStream.Init() just sets variables to default values But later we will call m_InBitStream.Init() again with real buffer pointers */ m_InBitStream.Init(); _needInitInStream = true; SetOutStreamSizeResume(outSize); return S_OK; } #ifndef NO_READ_FROM_CODER STDMETHODIMP CCoder::Read(void *data, UInt32 size, UInt32 *processedSize) { HRESULT res; if (processedSize) *processedSize = 0; const UInt64 outPos = GetOutProcessedCur(); bool finishInputStream = false; if (_outSizeDefined) { const UInt64 rem = _outSize - outPos; if (size >= rem) { size = (UInt32)rem; if (ZlibMode || _needFinishInput) finishInputStream = true; } } if (!finishInputStream && size == 0) return S_OK; DEFLATE_TRY_BEGIN m_OutWindowStream.SetMemStream((Byte *)data); res = CodeSpec(size, finishInputStream); DEFLATE_TRY_END(res) { HRESULT res2 = Flush(); if (res2 != S_OK) res = res2; } if (processedSize) *processedSize = (UInt32)(GetOutProcessedCur() - outPos); m_OutWindowStream.SetMemStream(NULL); return res; } #endif HRESULT CCoder::CodeResume(ISequentialOutStream *outStream, const UInt64 *outSize, ICompressProgressInfo *progress) { SetOutStreamSizeResume(outSize); return CodeReal(outStream, progress); } }}}
endlessm/rufus
endless/src/7z/CPP/7zip/Compress/DeflateDecoder.cpp
C++
gpl-3.0
12,300
/* * Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ /** * <p>This package contains interfaces and classes which shall enable users to describe their data formats * using an interpreted language by constructing an evaluatable tree of expressions. This gives much more * flexibility than working with a static type tree. * * * <p>This package is experimental and the interfaces and classes contained herein * currently not used in the <i>binio</i> API. * */ package com.bc.ceres.binio.expr;
arraydev/snap-engine
ceres-binio/src/main/java/com/bc/ceres/binio/expr/package-info.java
Java
gpl-3.0
1,167
<html> <?php if (!defined('BASEPATH')) exit ('No direct script access allowed');?> <?php $this->load->view('print/headjs.php');?> <body> <div id="content" class="container_12 clearfix"> <div id="content-main" class="grid_7"> <link href="<?= base_url()?>assets/css/surat.css" rel="stylesheet" type="text/css" /> <div> <table width="100%"> <tr> <img src="<?= LogoDesa($desa['logo']);?>" alt="" class="logo"></tr> <div class="header"> <h4 class="kop">PEMERINTAH <?= strtoupper($this->setting->sebutan_kabupaten)?> <?= strtoupper(unpenetration($desa['nama_kabupaten']))?> </h4> <h4 class="kop">KECAMATAN <?= strtoupper(unpenetration($desa['nama_kecamatan']))?> </h4> <h4 class="kop"><?= strtoupper($this->setting->sebutan_desa)?> <?= strtoupper(unpenetration($desa['nama_desa']))?></h4> <h5 class="kop2"><?= (unpenetration($desa['alamat_kantor']))?> </h5> <div style="text-align: center;"><hr /></div> </div> <div align="center"><u><h4 class="kop">SURAT PERMOHONAN WALI HAKIM</h4></u></div> <div align="center"><h4 class="kop3">Nomor : <?= $input['nomor']?></h4></div> </table> <div class="clear"></div> <table width="100%"> <tr> <td class="indentasi">Yang bertanda tangan dibawah ini <?= unpenetration($input['jabatan'])?> <?= unpenetration($desa['nama_desa'])?>, Kecamatan <?= unpenetration($desa['nama_kecamatan'])?>, <?= ucwords($this->setting->sebutan_kabupaten)?> <?= unpenetration($desa['nama_kabupaten'])?>, Provinsi <?= unpenetration($desa['nama_propinsi'])?> menerangkan dengan sebenarnya bahwa: </td></tr> </tr> </table> <div id="isi3"> <table width="100%"> <tr><td width="23%">Nama Lengkap</td><td width="3%">:</td><td width="64%"><?= unpenetration($data['nama'])?></td></tr> <tr><td width="23%">NIK/ No KTP</td><td width="3%">:</td><td width="64%"><?= $data['nik']?></td></tr> <tr><td>Tempat dan Tgl. Lahir </td><td>:</td><td><?= ($data['tempatlahir'])?>, <?= tgl_indo($data['tanggallahir'])?> </td></tr> <tr><td>Jenis Kelamin</td><td>:</td><td><?= $data['sex']?></td></tr> <tr><td>Alamat/ Tempat Tinggal</td><td>:</td><td>RT. <?= $data['rt']?>, RW. <?= $data['rw']?>, Dusun <?= unpenetration(ununderscore($data['dusun']))?>, <?= ucwords($this->setting->sebutan_desa)?> <?= unpenetration($desa['nama_desa'])?>, Kec. <?= unpenetration($desa['nama_kecamatan'])?>, <?= ucwords($this->setting->sebutan_kabupaten_singkat)?> <?= unpenetration($desa['nama_kabupaten'])?></td></tr> <tr><td>Agama</td><td>:</td><td><?= $data['agama']?></td></tr> <tr><td>Pekerjaan</td><td>:</td><td><?= $data['pekerjaan']?></td></tr> <tr><td>Kewarganegaraan </td><td>:</td><td><?= $data['warganegara']?></td></tr> <tr><td>Keterangan </td><td>:</td><td>Bahwa orang tersebut adalah benar-benar warga kami yang bertempat tinggal di Dusun <?= unpenetration(ununderscore($data['dusun']))?>, Rt. <?= $data['rt']?>, <?= unpenetration($desa['nama_desa'])?>, <?= unpenetration($desa['nama_kecamatan'])?>, <?= unpenetration($desa['nama_kabupaten'])?> akan menikah di KUA Kecamatan <?= unpenetration($desa['nama_kecamatan'])?> <?= ucwords($this->setting->sebutan_kabupaten)?> <?= unpenetration($desa['nama_kabupaten'])?>. Berhubung orang tersebut tidak mempunyai Wali Nasab, kami mohon dengan hormat Bapak Kepala KUA Kecamatan <?= unpenetration($desa['nama_kecamatan'])?> supaya berkenan menjadi Wali.</td></tr> </table> <table width="100%"> <tr></tr> <tr><td class="indentasi">Demikian Surat Keterangan ini kami buat untuk dapat dipergunakan sebagaimana mestinya. </td></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> </table> </div> <table width="100%"> <tr></tr> <tr></tr> <tr></tr> <tr><td width="10%"></td><td width="30%"></td><td align="center"><?= unpenetration($desa['nama_desa'])?>, <?= $tanggal_sekarang?></td></tr> <tr><td width="10%"></td><td width="30%"></td><td align="center"><?= unpenetration($input['jabatan'])?> <?= unpenetration($desa['nama_desa'])?></td></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr><td> <td></td><td align="center">( <?= unpenetration($input['pamong'])?> )</td></tr> </table> </div> </div> <div id="aside"></div> </div> </body> </html>
metalab25/OpenSID
surat/surat_ket_wali_hakim/print_surat_ket_wali_hakim.php
PHP
gpl-3.0
4,921
program sem_model_slice implicit none include 'mpif.h' include '../../SHARE_FILES/HEADER_FILES/constants.h' include '../../SHARE_FILES/HEADER_FILES/values_from_mesher.h' include '../../SHARE_FILES/HEADER_FILES/precision.h' integer,parameter:: NUM_NODES=99 ! for recent mesher 100 processors integer,parameter:: iregion=1 ! for region one integer,parameter:: NMAXPTS=10000000 real(kind=CUSTOM_REAL):: R_CUT_RANGE=0.00785d0 ! dr=0.00785 ~ 50 km depth integer::iproc,ipt,npts character(len=150):: xyz_infile,topo_dir,model_dir,filename,gmt_outfile character(len=256):: prname_topo, prname_file character(len=256):: topo_file, data_file real(kind=CUSTOM_REAL),dimension(NMAXPTS):: x,y,z real(kind=CUSTOM_REAL),dimension(NMAXPTS):: xfound,yfound,zfound,vfound real(kind=CUSTOM_REAL),dimension(NMAXPTS)::distmin,dist, distall, v, vall integer,dimension(NMAXPTS):: ispec_found,ix_found,iy_found,iz_found real(kind=CUSTOM_REAL),dimension(NGLOB_CRUST_MANTLE):: xstore, ystore, zstore integer,dimension(NGLLX,NGLLY,NGLLZ,NSPEC_CRUST_MANTLE):: ibool real(kind=CUSTOM_REAL),dimension(NGLLX,NGLLY,NGLLZ,NSPEC_CRUST_MANTLE):: vstore integer:: ier,sizeprocs,myrank,ios integer:: i,j,k,ispec,iglob real(kind=CUSTOM_REAL):: r,theta,phi,lat,lon,dep, xmesh,ymesh,zmesh real(kind=CUSTOM_REAL),dimension(2,NMAXPTS):: in,out real(kind=CUSTOM_REAL):: R_CUT, r1 call MPI_INIT(ier) call MPI_COMM_SIZE(MPI_COMM_WORLD,sizeprocs,ier) call MPI_COMM_RANK(MPI_COMM_WORLD,myrank,ier) ! read input file call get_command_argument(1,xyz_infile) call get_command_argument(2,topo_dir) call get_command_argument(3,model_dir) call get_command_argument(4,filename) call get_command_argument(5,gmt_outfile) ! read interpolate points if ( myrank == 0) then write(*,*) "INPUT FILE:", trim(xyz_infile) write(*,*) "TOPOLOGY FILE:", trim(topo_dir) write(*,*) "MODEL DIR:", trim(model_dir) write(*,*) "VALUE NAME:", trim(filename) write(*,*) "OUTPUT:", trim(gmt_outfile) endif open(1001,file=trim(xyz_infile),status='old',iostat=ios) i=0 do while (1 == 1) i=i+1 read(1001,*,iostat=ios) xmesh,ymesh,zmesh R_CUT=sqrt(xmesh**2+ymesh**2+zmesh**2) if (ios /= 0) exit x(i)=xmesh y(i)=ymesh z(i)=zmesh enddo close(1001) npts=i-1 !endif !call MPI_BCAST(npts,1,MPI_INTEGER,0,MPI_COMM_WORLD,ier) !call MPI_BCAST(x,NMAXPTS,CUSTOM_MPI_TYPE,0,MPI_COMM_WORLD,ier) !call MPI_BCAST(y,NMAXPTS,CUSTOM_MPI_TYPE,0,MPI_COMM_WORLD,ier) !call MPI_BCAST(z,NMAXPTS,CUSTOM_MPI_TYPE,0,MPI_COMM_WORLD,ier) if ( myrank == 0 ) then write(*,*) 'Total number of points = ', npts if (npts > NMAXPTS .or. npts < 0) call exit_MPI(myrank,'Npts error...') endif write(prname_topo,'(a,i6.6,a,i1,a)') trim(topo_dir)//'/proc',myrank,'_reg',iregion,'_' write(prname_file,'(a,i6.6,a,i1,a)') trim(model_dir)//'/proc',myrank,'_reg',iregion,'_' ! read value file data_file = trim(prname_file) // trim(filename) // '.bin' open(unit = 27,file = trim(data_file),status='old',action='read', iostat = ios,form ='unformatted') if (ios /= 0) call exit_MPI(myrank,'Error reading value file') read(27) vstore(:,:,:,1:NSPEC_CRUST_MANTLE) close(27) if (myrank == 0) write(*,*) 'DONE READING',trim(data_file) ! read topology topo_file = trim(prname_topo) // 'solver_data_2' // '.bin' open(unit = 28,file = trim(topo_file),status='old',action='read', iostat = ios, form='unformatted') if (ios /= 0) call exit_MPI(myrank,'Error reading topology file') xstore(:) = 0.0 ystore(:) = 0.0 zstore(:) = 0.0 ibool(:,:,:,:) = -1 read(28) xstore(1:NGLOB_CRUST_MANTLE) read(28) ystore(1:NGLOB_CRUST_MANTLE) read(28) zstore(1:NGLOB_CRUST_MANTLE) read(28) ibool(:,:,:,1:NSPEC_CRUST_MANTLE) close(28) if (myrank == 0) write(*,*) 'DONE READING',trim(topo_file) distmin(1:npts)=HUGEVAL do ispec=1,NSPEC_CRUST_MANTLE if (myrank == 0) write(*,*) 'ispec=',ispec do k = 1,NGLLZ do j = 1,NGLLY do i = 1,NGLLX iglob=ibool(i,j,k,ispec) r1=sqrt((xstore(iglob))**2+(ystore(iglob))**2+(zstore(iglob))**2) if ( abs(r1-R_CUT) < R_CUT_RANGE ) then dist(1:npts) = dsqrt((x(1:npts)-dble(xstore(iglob)))**2 & +(y(1:npts)-dble(ystore(iglob)))**2 & +(z(1:npts)-dble(zstore(iglob)))**2) do ipt=1,npts if (dist(ipt) < distmin(ipt)) then distmin(ipt)=dist(ipt) ispec_found(ipt)=ispec ix_found(ipt)=i iy_found(ipt)=j iz_found(ipt)=k vfound(ipt)=vstore(i,j,k,ispec) endif enddo ! ipt loop endif ! radius within in a range enddo ! i loop enddo ! j loop enddo ! k loop enddo ! ispec loop call MPI_BARRIER(MPI_COMM_WORLD,ier) if (myrank == 0) print *,'Done looping over global points' do i = 1,npts in(1,i)=distmin(i) in(2,i)=myrank enddo call MPI_REDUCE(in,out,npts,CUSTOM_MPI_2REAL,MPI_MINLOC,0,MPI_COMM_WORLD,ier) call MPI_BCAST(out,2*npts,CUSTOM_MPI_TYPE,0,MPI_COMM_WORLD,ier) v(1:npts)=0 dist(1:npts)=0. do i=1,npts if (myrank == nint(out(2,i))) then v(i)=vfound(i) dist(i)=distmin(i) endif enddo call MPI_REDUCE(v,vall,npts,CUSTOM_MPI_TYPE,MPI_SUM,0,MPI_COMM_WORLD,ier) call MPI_REDUCE(dist,distall,npts,CUSTOM_MPI_TYPE,MPI_SUM,0,MPI_COMM_WORLD,ier) if (myrank == 0) then open(1002, file=gmt_outfile,status='unknown') do i = 1,npts xmesh=x(i); ymesh=y(i); zmesh=z(i) call xyz_2_rthetaphi(xmesh,ymesh,zmesh,r,theta,phi) lat=90.0 - theta*180.0/PI lon=phi*180.0/PI dep=(1.0-r)*R_EARTH_KM ! write(1002,*) lon,lat,dep,vall(i),distall(i) write(1002,*) lon,lat,r,vall(i),distall(i) enddo close(1002) endif 202 FORMAT (5(F12.9,2X)) call MPI_FINALIZE(ier) end program sem_model_slice
vmont/specfem3d
utils/ADJOINT_TOMOGRAPHY_TOOLS/ADJOINT_TOMOGRAPHY_TOOLKIT/MODEL_VISULIZATION/SRC_MODEL_SLICE_HORIZ/sem_model_slice.f90
FORTRAN
gpl-3.0
6,127
#ifndef VOIPVIDEOLIB_GLOBAL_H #define VOIPVIDEOLIB_GLOBAL_H #include <QtCore/qglobal.h> #ifdef VOIPVIDEOLIB_LIB # define VOIPVIDEOLIB_EXPORT Q_DECL_EXPORT #else # define VOIPVIDEOLIB_EXPORT Q_DECL_IMPORT #endif #endif // VOIPVIDEOLIB_GLOBAL_H
silvansky/Contacts
src/thirdparty/siplibraries/VoIPVideoLib/Inc/voipvideolib_global.h
C
gpl-3.0
258
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'image', 'fa', { alertUrl: 'لطفا URL تصویر را بنویسید', alt: 'متن جایگزین', border: 'لبه', btnUpload: 'به سرور بفرست', button2Img: 'آیا مایلید از یک تصویر ساده روی دکمه تصویری انتخاب شده استفاده کنید؟', hSpace: 'فاصلهٴ افقی', img2Button: 'آیا مایلید از یک دکمه تصویری روی تصویر انتخاب شده استفاده کنید؟', infoTab: 'اطلاعات تصویر', linkTab: 'پیوند', lockRatio: 'قفل کردن نسبت', menu: 'ویژگی​های تصویر', resetSize: 'بازنشانی اندازه', title: 'ویژگی​های تصویر', titleButton: 'ویژگی​های دکمهٴ تصویری', upload: 'انتقال به سرور', urlMissing: 'آدرس URL اصلی تصویر یافت نشد.', vSpace: 'فاصلهٴ عمودی', validateBorder: 'مقدار خطوط باید یک عدد باشد.', validateHSpace: 'مقدار فاصله گذاری افقی باید یک عدد باشد.', validateVSpace: 'مقدار فاصله گذاری عمودی باید یک عدد باشد.' } );
joyofsrc/src
resources/ckeditor/plugins/image/lang/fa.js
JavaScript
gpl-3.0
1,366
# This file is part of Bioy # # Bioy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Bioy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Bioy. If not, see <http://www.gnu.org/licenses/>. """DEPRECATED: use the classifier subcommand Classify sequences by grouping blast output by matching taxonomic names Optional grouping by specimen and query sequences """ import sys import logging from csv import DictReader, DictWriter from collections import defaultdict from math import ceil from operator import itemgetter from bioy_pkg import sequtils from bioy_pkg.utils import Opener, opener, Csv2Dict, groupbyl log = logging.getLogger(__name__) def build_parser(parser): parser.add_argument('blast_file', nargs = '?', default = sys.stdin, type = Opener('r'), help = 'CSV tabular blast file of query and subject hits') parser.add_argument('--all-one-group', dest = 'all_one_group', action = 'store_true', help = """If --map is not provided, the default behavior is to treat all reads as one group; use this option to treat each read as a separate group [%(default)s]""") parser.add_argument('-a', '--asterisk', default = 100, metavar='PERCENT', type = float, help = 'Next to any species above a certain threshold [%(default)s]') parser.add_argument('--copy-numbers', metavar = 'CSV', type = Opener(), help = 'columns: tax_id, median') parser.add_argument('-c', '--coverage', default = 95, metavar = 'PERCENT', type = float, help = 'percent of alignment coverage of blast result [%(default)s]') parser.add_argument('--details-identity', metavar = 'PERCENT', help = 'Minimum identity to include blast hits in details file', type = float, default = 90) parser.add_argument('--details-full', action = 'store_true', help = 'do not limit out_details to only larget cluster per assignment') parser.add_argument('--exclude-by-taxid', metavar = 'CSV', type = lambda f: set(e for e in DictReader(opener(f), fieldnames ='tax_id')), default = {}, help = 'column: tax_id') parser.add_argument('--group-def', metavar = 'INT', action = 'append', default = [], help = """define a group threshold for a particular rank overriding --target-max-group-size. example: genus:2""") parser.add_argument('--group-label', metavar = 'LABEL', default = 'all', help = 'Single group label for reads') parser.add_argument('-o', '--out', default = sys.stdout, type = Opener('w'), metavar = 'CSV', help = """columns: specimen, max_percent, min_percent, max_coverage, min_coverage, assignment_id, assignment, clusters, reads, pct_reads, corrected, pct_corrected, target_rank, hi, low, tax_ids""") parser.add_argument('-m', '--map', metavar = 'CSV', type = Opener(), default = {}, help = 'columns: name, specimen') parser.add_argument('--max-ambiguous', metavar = 'INT', default = 3, type = int, help = 'Maximum ambiguous count in reference sequences [%(default)s]') parser.add_argument('--max-identity', default = 100, metavar = 'PERCENT', type = float, help = 'maximum identity threshold for accepting matches [<= %(default)s]') parser.add_argument('--min-cluster-size', default = 0, metavar = 'INT', type = int, help = 'minimum cluster size to include in classification output') parser.add_argument('--min-identity', default = 99, metavar = 'PERCENT', type = float, help = 'minimum identity threshold for accepting matches [> %(default)s]') parser.add_argument('-s', '--seq-info', required = True, metavar = 'CSV', type = Opener(), help = 'seq info file(s) to match sequence ids to taxids [%(default)s]') parser.add_argument('-t', '--taxonomy', required = True, metavar = 'CSV', type = Csv2Dict('tax_id'), help = 'tax table of taxids and species names [%(default)s]') parser.add_argument('-O', '--out-detail', type = lambda f: DictWriter(opener(f, 'w'), extrasaction = 'ignore', fieldnames = [ 'specimen', 'assignment', 'assignment_id', 'qseqid', 'sseqid', 'pident', 'coverage', 'ambig_count', 'accession', 'tax_id', 'tax_name', 'target_rank', 'rank', 'hi', 'low' ]), metavar = 'CSV', help = """columns: specimen, assignment, assignment_id, qseqid, sseqid, pident, coverage, ambig_count, accession, tax_id, tax_name, target_rank, rank, hi, low""") parser.add_argument('--target-max-group-size', metavar = 'INTEGER', default = 3, type = int, help = """group multiple target-rank assignments that excede a threshold to a higher rank [%(default)s]""") parser.add_argument('--target-rank', metavar='RANK', help = 'Rank at which to classify. Default: "%(default)s"', default = 'species') parser.add_argument('-w', '--weights', metavar = 'CSV', type = Opener(), help = 'columns: name, weight') ### csv.Sniffer.has_header is *not* reliable enough parser.add_argument('--has-header', action = 'store_true', help = 'specify this if blast data has a header') def coverage(start, end, length): return (float(end) - float(start) + 1) / float(length) * 100 def mean(l): l = list(l) return float(sum(l)) / len(l) if len(l) > 0 else 0 def condense(queries, floor_rank, max_size, ranks, rank_thresholds, target_rank = None): target_rank = target_rank or ranks[0] groups = list(groupbyl(queries, key = itemgetter(target_rank))) num_groups = len(groups) if rank_thresholds.get(target_rank, max_size) < num_groups: return queries # assign where available target_rank_ids # groups without 'i' values remain assigned at previous (higher) rank for g in (g for i,g in groups if i): for q in g: q['target_rank_id'] = q[target_rank] # return if we hit the floor if target_rank == floor_rank: return queries # else move down a rank target_rank = ranks[ranks.index(target_rank) + 1] # recurse down the tax tree condensed = [] for _,g in groups: c = condense(g, floor_rank, max_size, ranks, rank_thresholds, target_rank) condensed.extend(c) return condensed def action(args): ### format format blast data and add additional available information fieldnames = None if args.has_header else sequtils.BLAST_HEADER_DEFAULT blast_results = DictReader(args.blast_file, fieldnames = fieldnames) blast_results = list(blast_results) sseqids = set(s['sseqid'] for s in blast_results) qseqids = set(s['qseqid'] for s in blast_results) # load seq_info and map file mapfile = DictReader(args.map, fieldnames = ['name', 'specimen']) mapfile = {m['name']:m['specimen'] for m in mapfile if m['name'] in qseqids} seq_info = DictReader(args.seq_info) seq_info = {s['seqname']:s for s in seq_info if s['seqname'] in sseqids} # pident def pident(b): return dict(b, pident = float(b['pident'])) if b['sseqid'] else b blast_results = (pident(b) for b in blast_results) # coverage def cov(b): if b['sseqid'] and b['qcovs']: b['coverage'] = float(b['qcovs']) return b elif b['sseqid']: c = coverage(b['qstart'], b['qend'], b['qlen']) return dict(b, coverage = c) else: return b blast_results = (cov(b) for b in blast_results) # seq info def info(b): return dict(seq_info[b['sseqid']], **b) if b['sseqid'] else b blast_results = (info(b) for b in blast_results) # tax info def tax_info(b): return dict(args.taxonomy[b['tax_id']], **b) if b['sseqid'] else b blast_results = (tax_info(b) for b in blast_results) ### output file headers fieldnames = ['specimen', 'max_percent', 'min_percent', 'max_coverage', 'min_coverage', 'assignment_id', 'assignment'] if args.weights: weights = DictReader(args.weights, fieldnames = ['name', 'weight']) weights = {d['name']:d['weight'] for d in weights if d['name'] in qseqids} fieldnames += ['clusters', 'reads', 'pct_reads'] else: weights = {} if args.copy_numbers: copy_numbers = DictReader(args.copy_numbers) copy_numbers = {d['tax_id']:float(d['median']) for d in copy_numbers} fieldnames += ['corrected', 'pct_corrected'] else: copy_numbers = {} # TODO: take out target_rank, hi, low and provide in pipeline using csvmod # TODO: option to include tax_ids (default no) fieldnames += ['target_rank', 'hi', 'low', 'tax_ids'] ### Columns out = DictWriter(args.out, extrasaction = 'ignore', fieldnames = fieldnames) out.writeheader() if args.out_detail: args.out_detail.writeheader() def blast_hit(hit, args): return hit['sseqid'] and \ hit[args.target_rank] and \ hit['coverage'] >= args.coverage and \ float(weights.get(hit['qseqid'], 1)) >= args.min_cluster_size and \ hit[args.target_rank] not in args.exclude_by_taxid and \ hit['qseqid'] != hit['sseqid'] and \ int(hit['ambig_count']) <= args.max_ambiguous ### Rows etc = '[no blast result]' # This row will hold all unmatched # groups have list position prioritization groups = [ ('> {}%'.format(args.max_identity), lambda h: blast_hit(h, args) and h['pident'] > args.max_identity), (None, lambda h: blast_hit(h, args) and args.max_identity >= h['pident'] > args.min_identity), ('<= {}%'.format(args.min_identity), lambda h: blast_hit(h, args) and h['pident'] <= args.min_identity), ] # used later for results output group_cats = map(itemgetter(0), groups) group_cats.append(etc) # assignment rank thresholds rank_thresholds = (d.split(':') for d in args.group_def) rank_thresholds = dict((k, int(v)) for k,v in rank_thresholds) # rt = {k: int(v) for k, v in (d.split(':') for d in args.group_def)} # group by specimen if args.map: specimen_grouper = lambda s: mapfile[s['qseqid']] elif args.all_one_group: specimen_grouper = lambda s: args.group_label else: specimen_grouper = lambda s: s['qseqid'] blast_results = groupbyl(blast_results, key = specimen_grouper) assignments = [] # assignment list for assignment ids for specimen, hits in blast_results: categories = defaultdict(list) # clusters will hold the query ids as hits are matched to categories clusters = set() # filter out categories for cat, fltr in groups: matches = filter(fltr, hits) if cat: categories[cat] = matches else: # create sets of tax_rank_id query_group = groupbyl(matches, key = itemgetter('qseqid')) target_cats = defaultdict(list) for _,queries in query_group: queries = condense( queries, args.target_rank, args.target_max_group_size, sequtils.RANKS, rank_thresholds) cat = map(itemgetter('target_rank_id'), queries) cat = frozenset(cat) target_cats[cat].extend(queries) categories = dict(categories, **target_cats) # add query ids that were matched to a filter clusters |= set(map(itemgetter('qseqid'), matches)) # remove all hits corresponding to a matched query id (cluster) hits = filter(lambda h: h['qseqid'] not in clusters, hits) # remaining hits go in the etc ('no match') category categories[etc] = hits # calculate read counts read_counts = dict() for k,v in categories.items(): qseqids = set(map(itemgetter('qseqid'), v)) weight = sum(float(weights.get(q, 1)) for q in qseqids) read_counts[k] = weight taxids = set() for k,v in categories.items(): if k is not etc: for h in v: taxids.add(h['tax_id']) ### list of assigned ids for count corrections assigned_ids = dict() for k,v in categories.items(): if k is not etc and v: assigned_ids[k] = set(map(itemgetter('tax_id'), v)) # correction counts corrected_counts = dict() for k,v in categories.items(): if k is not etc and v: av = mean(copy_numbers.get(t, 1) for t in assigned_ids[k]) corrected_counts[k] = ceil(read_counts[k] / av) # finally take the root value for the etc category corrected_counts[etc] = ceil(read_counts[etc] / copy_numbers.get('1', 1)) # totals for percent calculations later total_reads = sum(v for v in read_counts.values()) total_corrected = sum(v for v in corrected_counts.values()) # Print classifications per specimen sorted by # of reads in reverse (descending) order sort_by_reads_assign = lambda (c,h): corrected_counts.get(c, None) for cat, hits in sorted(categories.items(), key = sort_by_reads_assign, reverse = True): # continue if their are hits if hits: # for incrementing assignment id's if cat not in assignments: assignments.append(cat) assignment_id = assignments.index(cat) reads = read_counts[cat] reads_corrected = corrected_counts[cat] clusters = set(map(itemgetter('qseqid'), hits)) results = dict( hi = args.max_identity, low = args.min_identity, target_rank = args.target_rank, specimen = specimen, assignment_id = assignment_id, reads = int(reads), pct_reads = '{0:.2f}'.format(reads / total_reads * 100), corrected = int(reads_corrected), pct_corrected = '{0:.2f}'.format(reads_corrected / total_corrected * 100), clusters = len(clusters)) if cat is etc: assignment = etc results = dict(results, assignment = assignment) else: taxids = set(map(itemgetter('tax_id'), hits)) coverages = set(map(itemgetter('coverage'), hits)) percents = set(map(itemgetter('pident'), hits)) if cat in group_cats: assignment = cat else: names = [args.taxonomy[h['target_rank_id']]['tax_name'] for h in hits] selectors = [h['pident'] >= args.asterisk for h in hits] assignment = sequtils.format_taxonomy(names, selectors, '*') results = dict(results, assignment = assignment, max_percent = '{0:.2f}'.format(max(percents)), min_percent = '{0:.2f}'.format(min(percents)), max_coverage = '{0:.2f}'.format(max(coverages)), min_coverage = '{0:.2f}'.format(min(coverages)), tax_ids = ' '.join(taxids)) out.writerow(results) if args.out_detail: if not args.details_full: # drop the no_hits hits = [h for h in hits if 'tax_id' in h] # only report heaviest centroid clusters_and_sizes = [(float(weights.get(c, 1.0)), c) for c in clusters] _, largest = max(clusters_and_sizes) hits = (h for h in hits if h['qseqid'] == largest) for h in hits: args.out_detail.writerow(dict( specimen = specimen, assignment = assignment, assignment_id = assignment_id, hi = args.max_identity, low = args.min_identity, target_rank = args.target_rank, **h))
nhoffman/bioy
bioy_pkg/subcommands/classify.py
Python
gpl-3.0
17,999
''' Created on Jul 28, 2013 @author: Rob ''' import os, yaml config = { 'names': [ 'NT', 'VGTestServer' ], 'servers':{ 'irc.server.tld': { 'port':6667, 'password':None, 'channels':{ '#vgstation': { 'nudges':True, 'status':True } } } }, 'plugins': { 'redmine': { 'url': '', 'apikey':'' }, 'nudge': { 'hostname': '', 'port': 45678, 'key': 'passwordgoeshere' } } } def ReadFromDisk(): global config config_file = 'config.yml' if not os.path.isfile(config_file): with open(config_file, 'w') as cw: yaml.dump(config, cw, default_flow_style=False) with open(config_file, 'r') as cr: config = yaml.load(cr) # if config['database']['username'] == '' or config['database']['password'] == '' or config['database']['schema'] == '': # print('!!! Default config.yml detected. Please edit it before continuing.') # sys.exit(1) def get(key,default=None): global config try: parts = key.split('.') value = config[parts[0]] if len(parts) == 1: return value for part in parts[1:]: value = value[part] return value except KeyError: return default
mph55/lanstation13
tools/bot/vgstation/common/config.py
Python
gpl-3.0
1,605
# $Id: strider.pm,v 1.6.4.2 2006/10/02 23:10:30 sendu Exp $ # BioPerl module for Bio::SeqIO::strider # # Cared for by Malcolm Cook <mec@stowers-institute.org> # # You may distribute this module under the same terms as perl itself # # _history # April 7th, 2005 Malcolm Cook authored # POD documentation - main docs before the code =head1 NAME Bio::SeqIO::strider - DNA strider sequence input/output stream =head1 SYNOPSIS Do not use this module directly. Use it via the Bio::SeqIO class. =head1 DESCRIPTION This object can transform Bio::Seq objects to and from strider 'binary' format, as documented in the strider manual, in which the first 112 bytes are a header, following by the sequence, followed by a sequence description. Note: it does NOT assign any sequence identifier, since they are not contained in the byte stream of the file; the Strider application simply displays the name of the file on disk as the name of the sequence. The caller should set the id, probably based on the name of the file (after possibly cleaning up whitespace, which ought not to be used as the id in most applications). Note: the strider 'comment' is mapped to the BioPerl 'description' (since there is no other text field, and description maps to defline text). =head1 FEEDBACK =head2 Mailing Lists User feedback is an integral part of the evolution of this and other Bioperl modules. Send your comments and suggestions preferably to one of the Bioperl mailing lists. Your participation is much appreciated. bioperl-l@bioperl.org - General discussion http://bioperl.org/wiki/Mailing_lists - About the mailing lists =head2 Reporting Bugs Report bugs to the Bioperl bug tracking system to help us keep track the bugs and their resolution. Bug reports can be submitted via the web: http://bugzilla.open-bio.org/ =head1 AUTHORS - Malcolm Cook Email: mec@stowers-institute.org =head1 CONTRIBUTORS Modelled after Bio::SeqIO::fasta by Ewan Birney E<lt>birney@ebi.ac.ukE<gt> and Lincoln Stein E<lt>lstein@cshl.orgE<gt> =head1 APPENDIX The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _ =cut # Let the code begin... package Bio::SeqIO::strider; use strict; use warnings; use Bio::Seq::SeqFactory; use Convert::Binary::C; use base qw(Bio::SeqIO); my $c = new Convert::Binary::C ( ByteOrder => 'BigEndian', Alignment => 2 ); my $headerdef; {local ($/); # See this file's __DATA__ section for the c structure definitions # for strider binary header data. Here we slurp it all into $headerdef. $headerdef = <DATA>}; $c->parse($headerdef); my $size_F_HEADER = 112; die "expected strider header structure size of $size_F_HEADER" unless $size_F_HEADER eq $c->sizeof('F_HEADER'); my %alphabet2type = ( # map between BioPerl alphabet and strider # sequence type code. # From Strider Documentation: the sequence type: # 1, 2, 3 and 4 for DNA, DNA Degenerate, RNA and # Protein sequence files, respectively. # TODO: determine 'DNA Degenerate' based on # sequence alphabet? dna => 1, rna => 3, protein => 4, ); my %type2alphabet = reverse %alphabet2type; sub _initialize { my($self,@args) = @_; $self->SUPER::_initialize(@args); unless ( defined $self->sequence_factory ) { $self->sequence_factory(Bio::Seq::SeqFactory->new(-verbose => $self->verbose(), -type => 'Bio::Seq::RichSeq')); } } =head2 next_seq Title : next_seq Usage : $seq = $stream->next_seq() Function: returns the next sequence in the stream Returns : Bio::Seq object Args : NONE =cut sub next_seq { my( $self ) = @_; my $fh = $self->_fh; my ($header,$sequence,$fulldesc); read $fh,$header,$size_F_HEADER or return ; #don't die here with "could not read header: $@" !!!; $self->throw("required $size_F_HEADER bytes while reading strider header in " . $self->{'_file'} . " but found: " . length($header)) unless $size_F_HEADER == length($header); my $headerdata = $c->unpack('F_HEADER',$header) or return; read $fh,$sequence,$headerdata->{nLength}; read $fh,$fulldesc,$headerdata->{com_length}; $fulldesc =~ s/\cM/ /g; # gratuitous replacement of mac # linefeed with space. my $seq = $self->sequence_factory->create( # -id => $main::ARGV, #might want to set this in caller to $ARGV. -seq => $sequence, -desc => $fulldesc, -alphabet => $type2alphabet{$headerdata->{type}} || 'dna', ); return $seq; } =head2 write_seq Title : write_seq Usage : $stream->write_seq(@seq) Function: writes the $seq object into the stream Returns : 1 for success and 0 for error Args : array of 1 to n Bio::PrimarySeqI objects =cut sub write_seq { my ($self,@seq) = @_; my $fh = $self->_fh() || *STDOUT; #die "could not determine filehandle in strider.pm"; foreach my $seq (@seq) { $self->throw("Did not provide a valid Bio::PrimarySeqI object") unless defined $seq && ref($seq) && $seq->isa('Bio::PrimarySeqI'); my $headerdata = $c->pack('F_HEADER',{ versionNb => 0, type => $alphabet2type{$seq->alphabet} || $alphabet2type{dna}, topology => $seq->is_circular ? 1 : 0, nLength => $seq->length, nMinus => 0, com_length => length($seq->desc || ""), }); print $fh $headerdata, $seq->seq() || "" , $seq->desc || ""; } } 1; __DATA__ //The following was taken from the strider 1.4 release notes Appendix (with //some comments gleaned from other parts of manual) struct F_HEADER { char versionNb; // the format version number, currently it is set to 0 char type; // 1=DNA, 2=DNA Degenerate, 3=RNA or 4=Protein char topology; // linear or circular - 0 for a linear sequence, 1 for a circular one char reserved1; int reserved2; int reserved3; int reserved4; char reserved5; char filler1; short filler2; int filler3; int reserved6; int nLength; // Sequence length - the length the Sequence field (the number of char in the text, each being a base or an aa) int nMinus; // nb of "negative" bases, i.e. the number of bases numbered with negative numbers int reserved7; int reserved8; int reserved9; int reserved10; int reserved11; char reserved12[32]; short reserved13; short filler4; char reserved14; char reserved15; char reserved16; char filler5; int com_length; // the length the Comment field (the number of char in the text). int reserved17; int filler6; int filler7; };
vinuesa/get_phylomarkers
lib/perl/bioperl-1.5.2_102/Bio/SeqIO/strider.pm
Perl
gpl-3.0
6,620
var spawn = require('child_process').spawn var express = require('express') var assets = __dirname + "/../../static" var server = express() server.use(express.cookieParser(' default ')) server.use(express.session({secret:' default '})) server.use(express.bodyParser()) server.use(express.static(assets)) server.get('/', function(req, res){ res.send( '<html>' + '<body>' + '<button>Test</button>' + '<script src="/jq.js"></script>' + '<script>$("button").click(function(){' + 'var windowObjectReference;' + 'function openRequestedPopup(data) {' + 'windowObjectReference = window.open("/preview/pdf", "Preview", strWindowFeatures);' + '}' + 'var strWindowFeatures = "menubar=no,location=no,resizable=no,scrollbars=no,status=no";' + '$.post("/preview/render", { data : {"body" : "<b>This is <i>a cool</i> test</b> converting html to pdf via stdout <i>stream</i>"}}, function(data){ openRequestedPopup(data) })' + '})</script>' + '</body></html>') }) server.get('/preview/pdf', function(req, res){ var preview = spawn('phantomjs', [__dirname + '/../../simaya/controller/scripts/pdf.js', req.session.data]) res.set('Content-type', 'application/pdf') preview.stdout.pipe(res) }) server.post('/preview/render', function(req, res){ req.session.data = req.body.data.body res.send({}) }) server.listen(8000)
blackmonk88/simaya
attic/test/preview/preview.js
JavaScript
gpl-3.0
1,368
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package kolonistenvancatan; import domein.Spel; import domein.Speler; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.awt.Color; /** * * @author E.Muit-Laptop */ public class Lobby extends UnicastRemoteObject implements ILobby { public ArrayList<Speler> spelers = new ArrayList<Speler>(); public ArrayList<Spel> spellen = new ArrayList<Spel>(); public String chatTekst = ""; public Lobby() throws RemoteException { } public String getChatTekst() { return chatTekst; } @Override public void plaatsBericht(String bericht, String speler) throws RemoteException { chatTekst += speler + ": " + bericht + "\n"; } @Override public void addSpeler(String naam) throws RemoteException { Speler s = new Speler(naam, null); spelers.add(s); } @Override public void removeSpeler(Speler speler) throws RemoteException { spelers.remove(speler); } @Override public ArrayList<String> getSpelers() { ArrayList<String> returnwaarde = new ArrayList<String>(); for (Speler s : spelers) { returnwaarde.add(s.getNaam()); } return returnwaarde; } @Override public int getAantalSpelers() throws RemoteException { return spelers.size(); } @Override public void addSpel(String s) throws RemoteException { boolean spelBestaatAl = false; for (Spel spel : spellen) { if (spel.getNaam().equals(s)) spelBestaatAl=true; } if (!spelBestaatAl) spellen.add(new Spel(s)); } @Override public ArrayList<String> getSpellen() throws RemoteException { ArrayList<String> returnwaarde = new ArrayList<String>(); for (Spel s : spellen) { returnwaarde.add(s.getNaam()); } return returnwaarde; } @Override public int getAantalSpellen() throws RemoteException { return spellen.size(); } @Override public Spel getSpel(String naam) throws RemoteException { for (Spel s : spellen) if (s.getNaam().equals(naam)) return s; return null; } public void voegSpelerToeAanSpel(Speler speler, String spel) { for (Spel s : spellen) { if (s.getNaam().equals(spel)) { //s.addspeler(speler); System.out.println(speler.getNaam() +" toegevoegd aan "+ spel); } } } }
FHICT-Software/P3P4
PTS/KolonistenVanCatan/KolonistenVanCatan_USB/src/kolonistenvancatan/Lobby.java
Java
gpl-3.0
2,864
<?php /* * This file is part of Phraseanet * * (c) 2005-2015 Alchemy * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Alchemy\Phrasea\Command\Command; class module_console_fieldsList extends Command { public function __construct($name = null) { parent::__construct($name); $this->setDescription('Lists all databoxes documentation fields'); return $this; } protected function doExecute(InputInterface $input, OutputInterface $output) { foreach ($this->getService('phraseanet.appbox')->get_databoxes() as $databox) { /* @var $databox \databox */ $output->writeln( sprintf( "\n ---------------- \nOn databox %s (sbas_id %d) :\n" , $databox->get_label($this->container['locale']) , $databox->get_sbas_id() ) ); foreach ($databox->get_meta_structure()->get_elements() as $field) { $output->writeln( sprintf( " %2d - <info>%s</info> (%s) %s" , $field->get_id() , $field->get_name() , $field->get_type() , ($field->is_multi() ? '<comment>multi</comment>' : '') ) ); } } return 0; } }
kwemi/Phraseanet
lib/classes/module/console/fieldsList.php
PHP
gpl-3.0
1,601
#include "Button.hpp" Button::Button( rapidxml::xml_node<> * node ) : ATag( node ) { } void Button::init( CoreEngine & coreEngine ) { }
Geko-io/CommunityGame-Engine
srcs/ui/tag/Button.cpp
C++
gpl-3.0
140
/* $Id: KVINDRAIdentRoot.h,v 1.2 2006/10/19 14:32:43 franklan Exp $ $Revision: 1.2 $ $Date: 2006/10/19 14:32:43 $ */ #ifndef KVINDRAIdentRoot_h #define KVINDRAIdentRoot_h #include "KVOldINDRASelector.h" class TFile; class TTree; class KVINDRAIdentRoot: public KVOldINDRASelector { int codes[15]; int status[4]; int Acodes[15]; int Astatus[4]; protected: TFile* fIdentFile; //new file TTree* fIdentTree; //new tree Int_t fRunNumber; Int_t fEventNumber; public: KVINDRAIdentRoot() { fIdentFile = 0; fIdentTree = 0; }; virtual ~ KVINDRAIdentRoot() { }; virtual void InitRun(); virtual void EndRun(); virtual void InitAnalysis(); virtual Bool_t Analysis(); virtual void EndAnalysis(); void CountStatus(); void CountCodes(); ClassDef(KVINDRAIdentRoot, 0);//Generation of fully-identified and calibrated INDRA data files }; #endif
FableQuentin/kaliveda
KVIndra/analysis/KVINDRAIdentRoot.h
C
gpl-3.0
935
module.exports = function dendro_shade_bars(params, inst_selection, inst_rc, inst_data){ var inst_opacity = 0.2; var bot_height; d3.selectAll(params.root+' .dendro_shadow') .remove(); if (inst_rc == 'row'){ // top shade d3.select(params.root+' .clust_group') .append('rect') .attr('width', params.viz.clust.dim.width+'px') .attr('height', inst_data.pos_top+'px') .attr('fill','black') .classed('dendro_shadow',true) .attr('opacity', inst_opacity); bot_height = params.viz.clust.dim.height - inst_data.pos_bot; // bottom shade d3.select(params.root+' .clust_group') .append('rect') .attr('width', params.viz.clust.dim.width+'px') .attr('height', bot_height+'px') .attr('transform','translate(0,'+inst_data.pos_bot+')') .attr('fill','black') .classed('dendro_shadow',true) .attr('opacity', inst_opacity); } else if (inst_rc === 'col'){ // top shade d3.select(params.root+' .clust_group') .append('rect') .attr('width', inst_data.pos_top+'px') .attr('height', params.viz.clust.dim.height+'px') .attr('fill','black') .classed('dendro_shadow',true) .attr('opacity', inst_opacity); // bottom shade bot_height = params.viz.clust.dim.width - inst_data.pos_bot; d3.select(params.root+' .clust_group') .append('rect') .attr('width', bot_height+'px') .attr('height', params.viz.clust.dim.height+'px') .attr('transform','translate('+inst_data.pos_bot+',0)') .attr('fill','black') .classed('dendro_shadow',true) .attr('opacity',inst_opacity); } };
cornhundred/clustergrammer.js
src/dendrogram/dendro_shade_bars.js
JavaScript
gpl-3.0
1,656
/* -*- c++ -*- * Copyright (C) 2007-2016 Hypertable, Inc. * * This file is part of Hypertable. * * Hypertable is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or any later version. * * Hypertable is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ /// @file /// Declarations for Rmdir request parameters. /// This file contains declarations for Rmdir, a class for encoding and /// decoding paramters to the <i>rmdir</i> file system broker function. #ifndef FsBroker_Lib_Request_Parameters_Rmdir_h #define FsBroker_Lib_Request_Parameters_Rmdir_h #include <Common/Serializable.h> #include <string> using namespace std; namespace Hypertable { namespace FsBroker { namespace Lib { namespace Request { namespace Parameters { /// @addtogroup FsBrokerLibRequestParameters /// @{ /// %Request parameters for <i>rmdir</i> requests. class Rmdir : public Serializable { public: /// Constructor. /// Empty initialization for decoding. Rmdir() {} /// Constructor. /// Initializes with parameters for encoding. Sets #m_dirname to /// <code>dirname</code>. /// @param dirname Directory name Rmdir(const std::string &dirname) : m_dirname(dirname) {} /// Gets directory name /// @return Directory name const char *get_dirname() { return m_dirname.c_str(); } private: uint8_t encoding_version() const override; size_t encoded_length_internal() const override; void encode_internal(uint8_t **bufp) const override; void decode_internal(uint8_t version, const uint8_t **bufp, size_t *remainp) override; /// Directory name std::string m_dirname; }; /// @} }}}}} #endif // FsBroker_Lib_Request_Parameters_Rmdir_h
hypertable/hypertable
src/cc/FsBroker/Lib/Request/Parameters/Rmdir.h
C
gpl-3.0
2,256
package packngo import "fmt" const ipBasePath = "/ips" // IPService interface defines available IP methods type IPService interface { Assign(deviceID string, assignRequest *IPAddressAssignRequest) (*IPAddress, *Response, error) Unassign(ipAddressID string) (*Response, error) Get(ipAddressID string) (*IPAddress, *Response, error) } // IPAddress represents a ip address type IPAddress struct { ID string `json:"id"` Address string `json:"address"` Gateway string `json:"gateway"` Network string `json:"network"` AddressFamily int `json:"address_family"` Netmask string `json:"netmask"` Public bool `json:"public"` Cidr int `json:"cidr"` AssignedTo map[string]string `json:"assigned_to"` Created string `json:"created_at,omitempty"` Updated string `json:"updated_at,omitempty"` Href string `json:"href"` Facility Facility `json:"facility,omitempty"` } // IPAddressAssignRequest represents the body if a ip assign request type IPAddressAssignRequest struct { Address string `json:"address"` } func (i IPAddress) String() string { return Stringify(i) } // IPServiceOp implements IPService type IPServiceOp struct { client *Client } // Get returns IpAddress by ID func (i *IPServiceOp) Get(ipAddressID string) (*IPAddress, *Response, error) { path := fmt.Sprintf("%s/%s", ipBasePath, ipAddressID) req, err := i.client.NewRequest("GET", path, nil) if err != nil { return nil, nil, err } ip := new(IPAddress) resp, err := i.client.Do(req, ip) if err != nil { return nil, resp, err } return ip, resp, err } // Unassign unassigns an IP address record. This will remove the relationship between an IP // and the device and will make the IP address available to be assigned to another device. func (i *IPServiceOp) Unassign(ipAddressID string) (*Response, error) { path := fmt.Sprintf("%s/%s", ipBasePath, ipAddressID) req, err := i.client.NewRequest("DELETE", path, nil) if err != nil { return nil, err } resp, err := i.client.Do(req, nil) return resp, err } // Assign assigns an IP address to a device. The IP address must be in one of the IP ranges assigned to the device’s project. func (i *IPServiceOp) Assign(deviceID string, assignRequest *IPAddressAssignRequest) (*IPAddress, *Response, error) { path := fmt.Sprintf("%s/%s%s", deviceBasePath, deviceID, ipBasePath) req, err := i.client.NewRequest("POST", path, assignRequest) ip := new(IPAddress) resp, err := i.client.Do(req, ip) if err != nil { return nil, resp, err } return ip, resp, err } // IP RESERVATIONS API // IPReservationService interface defines available IPReservation methods type IPReservationService interface { List(projectID string) ([]IPReservation, *Response, error) RequestMore(projectID string, ipReservationReq *IPReservationRequest) (*IPReservation, *Response, error) Get(ipReservationID string) (*IPReservation, *Response, error) Remove(ipReservationID string) (*Response, error) } // IPReservationServiceOp implements the IPReservationService interface type IPReservationServiceOp struct { client *Client } // IPReservationRequest represents the body of a reservation request type IPReservationRequest struct { Type string `json:"type"` Quantity int `json:"quantity"` Comments string `json:"comments"` } // IPReservation represent an IP reservation for a single project type IPReservation struct { ID string `json:"id"` Network string `json:"network"` Address string `json:"address"` AddressFamily int `json:"address_family"` Netmask string `json:"netmask"` Public bool `json:"public"` Cidr int `json:"cidr"` Management bool `json:"management"` Manageable bool `json:"manageable"` Addon bool `json:"addon"` Bill bool `json:"bill"` Assignments []map[string]string `json:"assignments"` Created string `json:"created_at,omitempty"` Updated string `json:"updated_at,omitempty"` Href string `json:"href"` } type ipReservationRoot struct { IPReservations []IPReservation `json:"ip_addresses"` } // List provides a list of IP resevations for a single project. func (i *IPReservationServiceOp) List(projectID string) ([]IPReservation, *Response, error) { path := fmt.Sprintf("%s/%s%s", projectBasePath, projectID, ipBasePath) req, err := i.client.NewRequest("GET", path, nil) if err != nil { return nil, nil, err } reservations := new(ipReservationRoot) resp, err := i.client.Do(req, reservations) if err != nil { return nil, resp, err } return reservations.IPReservations, resp, err } // RequestMore requests more IP space for a project in order to have additional IP addresses to assign to devices func (i *IPReservationServiceOp) RequestMore(projectID string, ipReservationReq *IPReservationRequest) (*IPReservation, *Response, error) { path := fmt.Sprintf("%s/%s%s", projectBasePath, projectID, ipBasePath) req, err := i.client.NewRequest("POST", path, &ipReservationReq) if err != nil { return nil, nil, err } ip := new(IPReservation) resp, err := i.client.Do(req, ip) if err != nil { return nil, resp, err } return ip, resp, err } // Get returns a single IP reservation object func (i *IPReservationServiceOp) Get(ipReservationID string) (*IPReservation, *Response, error) { path := fmt.Sprintf("%s/%s", ipBasePath, ipReservationID) req, err := i.client.NewRequest("GET", path, nil) if err != nil { return nil, nil, err } reservation := new(IPReservation) resp, err := i.client.Do(req, reservation) if err != nil { return nil, nil, err } return reservation, resp, err } // Remove removes an IP reservation from the project. func (i *IPReservationServiceOp) Remove(ipReservationID string) (*Response, error) { path := fmt.Sprintf("%s/%s", ipBasePath, ipReservationID) req, err := i.client.NewRequest("DELETE", path, nil) if err != nil { return nil, err } resp, err := i.client.Do(req, nil) if err != nil { return nil, err } return resp, err }
MustWin/terraform-provider-baremetal
vendor/github.com/packethost/packngo/ip.go
GO
mpl-2.0
6,385
/** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations under * the License. * * The Original Code is OpenELIS code. * * Copyright (C) The Minnesota Department of Health. All Rights Reserved. * * Contributor(s): CIRG, University of Washington, Seattle WA. */ package us.mn.state.health.lims.note.daoimpl; import org.apache.commons.beanutils.PropertyUtils; import org.hibernate.HibernateException; import org.hibernate.Query; import us.mn.state.health.lims.audittrail.dao.AuditTrailDAO; import us.mn.state.health.lims.audittrail.daoimpl.AuditTrailDAOImpl; import us.mn.state.health.lims.common.action.IActionConstants; import us.mn.state.health.lims.common.daoimpl.BaseDAOImpl; import us.mn.state.health.lims.common.exception.LIMSDuplicateRecordException; import us.mn.state.health.lims.common.exception.LIMSRuntimeException; import us.mn.state.health.lims.common.log.LogEvent; import us.mn.state.health.lims.common.util.StringUtil; import us.mn.state.health.lims.common.util.SystemConfiguration; import us.mn.state.health.lims.hibernate.HibernateUtil; import us.mn.state.health.lims.note.dao.NoteDAO; import us.mn.state.health.lims.note.valueholder.Note; import java.sql.Date; import java.util.List; /** * @author diane benz */ public class NoteDAOImpl extends BaseDAOImpl implements NoteDAO { public void deleteData(List notes) throws LIMSRuntimeException { try { AuditTrailDAO auditDAO = new AuditTrailDAOImpl(); for( Object note : notes ){ Note data = ( Note ) note; Note oldData = readNote( data.getId() ); Note newData = new Note(); String sysUserId = data.getSysUserId(); String event = IActionConstants.AUDIT_TRAIL_DELETE; String tableName = "NOTE"; auditDAO.saveHistory( newData, oldData, sysUserId, event, tableName ); } } catch (Exception e) { LogEvent.logError("NoteDAOImpl","AuditTrail deleteData()",e.toString()); throw new LIMSRuntimeException("Error in Note AuditTrail deleteData()", e); } try { for( Object note : notes ){ Note data = ( Note ) note; data = readNote( data.getId() ); HibernateUtil.getSession().delete( data ); HibernateUtil.getSession().flush(); HibernateUtil.getSession().clear(); } } catch (Exception e) { LogEvent.logError("NoteDAOImpl","deleteData()",e.toString()); throw new LIMSRuntimeException("Error in Note deleteData()",e); } } public boolean insertData(Note note) throws LIMSRuntimeException { try { String id = (String) HibernateUtil.getSession().save(note); note.setId(id); AuditTrailDAO auditDAO = new AuditTrailDAOImpl(); String sysUserId = note.getSysUserId(); String tableName = "NOTE"; auditDAO.saveNewHistory(note,sysUserId,tableName); HibernateUtil.getSession().flush(); HibernateUtil.getSession().clear(); } catch (Exception e) { LogEvent.logError("NoteDAOImpl","insertData()",e.toString()); throw new LIMSRuntimeException("Error in Note insertData()", e); } return true; } public void updateData(Note note) throws LIMSRuntimeException { try { if (duplicateNoteExists(note)) { throw new LIMSDuplicateRecordException( "Duplicate record exists for " + note.getNoteType() + " " + note.getSubject()); } } catch (Exception e) { LogEvent.logError("NoteDAOImpl","updateData()",e.toString()); throw new LIMSRuntimeException("Error in Note updateData()", e); } Note oldData = readNote(note.getId()); try { AuditTrailDAO auditDAO = new AuditTrailDAOImpl(); String sysUserId = note.getSysUserId(); String event = IActionConstants.AUDIT_TRAIL_UPDATE; String tableName = "NOTE"; auditDAO.saveHistory(note,oldData,sysUserId,event,tableName); } catch (Exception e) { LogEvent.logError("NoteDAOImpl","AuditTrail updateData()",e.toString()); throw new LIMSRuntimeException("Error in Note AuditTrail updateData()", e); } try { HibernateUtil.getSession().merge(note); HibernateUtil.getSession().flush(); HibernateUtil.getSession().clear(); HibernateUtil.getSession().evict(note); HibernateUtil.getSession().refresh(note); } catch (Exception e) { LogEvent.logError("NoteDAOImpl","updateData()",e.toString()); throw new LIMSRuntimeException("Error in Note updateData()", e); } } public void getData(Note note) throws LIMSRuntimeException { try { Note nt = (Note) HibernateUtil.getSession().get(Note.class, note.getId()); HibernateUtil.getSession().flush(); HibernateUtil.getSession().clear(); if (nt != null) { PropertyUtils.copyProperties(note, nt); } else { note.setId(null); } } catch (Exception e) { LogEvent.logError("NoteDAOImpl","getData()",e.toString()); throw new LIMSRuntimeException("Error in Note getData()", e); } } @Override public Note getData(String noteId) throws LIMSRuntimeException { try { Note note = (Note) HibernateUtil.getSession().get(Note.class, noteId); closeSession(); return note; } catch (Exception e) { handleException(e, "getData"); } return null; } @SuppressWarnings("unchecked") public List<Note> getAllNotes() throws LIMSRuntimeException { List<Note> list; try { String sql = "from Note"; Query query = HibernateUtil.getSession().createQuery(sql); list = query.list(); HibernateUtil.getSession().flush(); HibernateUtil.getSession().clear(); } catch (Exception e) { LogEvent.logError("NoteDAOImpl","getAllNotes()",e.toString()); throw new LIMSRuntimeException("Error in Note getAllNotes()", e); } return list; } public List getPageOfNotes(int startingRecNo) throws LIMSRuntimeException { List list; try { // calculate maxRow to be one more than the page size int endingRecNo = startingRecNo + (SystemConfiguration.getInstance().getDefaultPageSize() + 1); //bugzilla 2571 go through ReferenceTablesDAO to get reference tables info String sql = "from Note nt order by nt.referenceTableId, nt.referenceId,nt.noteType"; org.hibernate.Query query = HibernateUtil.getSession().createQuery( sql); query.setFirstResult(startingRecNo - 1); query.setMaxResults(endingRecNo - 1); list = query.list(); HibernateUtil.getSession().flush(); HibernateUtil.getSession().clear(); } catch (Exception e) { LogEvent.logError("NoteDAOImpl","getPageOfNotes()",e.toString()); throw new LIMSRuntimeException( "Error in Note getPageOfNotes()", e); } return list; } public Note readNote(String idString) { Note note; try { note = (Note) HibernateUtil.getSession().get(Note.class, idString); HibernateUtil.getSession().flush(); HibernateUtil.getSession().clear(); } catch (Exception e) { LogEvent.logError("NoteDAOImpl","readNote()",e.toString()); throw new LIMSRuntimeException("Error in Note readNote()", e); } return note; } public List getNextNoteRecord(String id) throws LIMSRuntimeException { return null;//getNextRecord(id, "Note", Note.class); } public List getPreviousNoteRecord(String id) throws LIMSRuntimeException { return null;//getPreviousRecord(id, "Note", Note.class); } public List getAllNotesByRefIdRefTable(Note note) throws LIMSRuntimeException { try { String sql = "from Note n where n.referenceId = :refId and n.referenceTableId = :refTableId order by n.noteType desc, n.lastupdated desc"; org.hibernate.Query query = HibernateUtil.getSession().createQuery( sql); query.setInteger("refId", Integer.parseInt(note.getReferenceId())); query.setInteger("refTableId", Integer.parseInt(note.getReferenceTableId())); List list = query.list(); HibernateUtil.getSession().flush(); HibernateUtil.getSession().clear(); return list; } catch (Exception e) { LogEvent.logError("NoteDAOImpl","getAllNotesByRefIdRefTable()",e.toString()); throw new LIMSRuntimeException("Error in Note getAllNotesByRefIdRefTable()", e); } } @SuppressWarnings("unchecked") public List<Note> getNotesByNoteTypeRefIdRefTable(Note note) throws LIMSRuntimeException { try { String sql = "from Note n where n.referenceId = :refId and n.referenceTableId = :refTableId and n.noteType = :noteType order by n.lastupdated"; org.hibernate.Query query = HibernateUtil.getSession().createQuery( sql); query.setInteger("refId", Integer.parseInt(note.getReferenceId())); query.setInteger("refTableId", Integer.parseInt(note.getReferenceTableId())); query.setParameter("noteType", note.getNoteType()); List<Note> list = query.list(); HibernateUtil.getSession().flush(); HibernateUtil.getSession().clear(); return list; } catch (Exception e) { LogEvent.logError("NoteDAOImpl","getNotesByNoteTypeRefIdRefTable()",e.toString()); throw new LIMSRuntimeException("Error in Note getNotesByNoteTypeRefIdRefTable()", e); } } public Integer getTotalNoteCount() throws LIMSRuntimeException { return getTotalCount("Note", Note.class); } public List getNextRecord(String id, String table, Class clazz) throws LIMSRuntimeException { int currentId = Integer.valueOf( id ); String tablePrefix = getTablePrefix(table); List list; int rrn; try { String sql = "select n.id from Note n " + " order by n.referenceTableId, n.referenceId, n.noteType"; org.hibernate.Query query = HibernateUtil.getSession().createQuery(sql); list = query.list(); HibernateUtil.getSession().flush(); HibernateUtil.getSession().clear(); rrn = list.indexOf(String.valueOf(currentId)); list = HibernateUtil.getSession().getNamedQuery(tablePrefix + "getNext") .setFirstResult(rrn + 1) .setMaxResults(2) .list(); } catch (Exception e) { LogEvent.logError("NoteDAOImpl","getNextRecord()",e.toString()); throw new LIMSRuntimeException("Error in getNextRecord() for " + table, e); } return list; } public List getPreviousRecord(String id, String table, Class clazz) throws LIMSRuntimeException { int currentId = Integer.valueOf( id ); String tablePrefix = getTablePrefix(table); List list; int rrn; try { String sql = "select n.id from Note n " + " order by n.referenceTableId desc, n.referenceId desc, n.noteType desc"; org.hibernate.Query query = HibernateUtil.getSession().createQuery(sql); list = query.list(); HibernateUtil.getSession().flush(); HibernateUtil.getSession().clear(); rrn = list.indexOf(String.valueOf(currentId)); list = HibernateUtil.getSession().getNamedQuery( tablePrefix + "getPrevious").setFirstResult( rrn + 1).setMaxResults(2).list(); } catch (Exception e) { LogEvent.logError("NoteDAOImpl","getPreviousRecord()",e.toString()); throw new LIMSRuntimeException("Error in getPreviousRecord() for " + table, e); } return list; } @SuppressWarnings("unchecked") private boolean duplicateNoteExists(Note note) throws LIMSRuntimeException { try { List<Note> list; String sql = "from Note t where trim(lower(t.noteType)) = :noteType and t.referenceId = :referenceId and t.referenceTableId = :referenceTableId and trim(lower(t.text)) = :param4 and trim(lower(t.subject)) = :param5 and t.id != :noteId"; org.hibernate.Query query = HibernateUtil.getSession().createQuery( sql); query.setParameter("noteType", note.getNoteType().toLowerCase().trim()); query.setInteger("referenceId", Integer.parseInt(note.getReferenceId())); query.setInteger("referenceTableId", Integer.parseInt(note.getReferenceTableId())); query.setParameter("param4", note.getText().toLowerCase().trim()); query.setParameter("param5", note.getSubject().toLowerCase().trim()); int noteId = !StringUtil.isNullorNill(note.getId()) ?Integer.parseInt(note.getId()) : 0; query.setInteger("noteId", noteId); list = query.list(); HibernateUtil.getSession().flush(); HibernateUtil.getSession().clear(); return list.size() > 0; } catch (Exception e) { LogEvent.logError("NoteDAOImpl","duplicateNoteExists()",e.toString()); throw new LIMSRuntimeException("Error in duplicateNoteExists()", e); } } @SuppressWarnings("unchecked") @Override public List<Note> getNoteByRefIAndRefTableAndSubject(String refId, String table_id, String subject) throws LIMSRuntimeException { String sql = "FROM Note n where n.referenceId = :refId and n.referenceTableId = :tableId and n.subject = :subject"; try{ Query query = HibernateUtil.getSession().createQuery(sql); query.setInteger("refId", Integer.parseInt(refId)); query.setInteger("tableId", Integer.parseInt(table_id)); query.setString("subject", subject); List<Note> noteList = query.list(); closeSession(); return noteList; }catch(HibernateException e){ handleException(e, "getNoteByRefIAndRefTableAndSubject"); } return null; } @Override @SuppressWarnings( "unchecked" ) public List<Note> getNotesChronologicallyByRefIdAndRefTable( String refId, String table_id ) throws LIMSRuntimeException{ String sql = "FROM Note n where n.referenceId = :refId and n.referenceTableId = :tableId order by n.lastupdated asc"; try{ Query query = HibernateUtil.getSession().createQuery(sql); query.setInteger("refId", Integer.parseInt(refId)); query.setInteger("tableId", Integer.parseInt(table_id)); List<Note> noteList = query.list(); closeSession(); return noteList; }catch(HibernateException e){ handleException(e, "getNotesChronologicallyByRefIdAndRefTable"); } return null; } @Override @SuppressWarnings( "unchecked" ) public List<Note> getNotesChronologicallyByRefIdAndRefTableAndType( String objectId, String tableId, List<String> filter ) throws LIMSRuntimeException{ String sql = "FROM Note n where n.referenceId = :refId and n.referenceTableId = :tableId and n.noteType in ( :filter ) order by n.lastupdated asc"; try{ Query query = HibernateUtil.getSession().createQuery(sql); query.setInteger("refId", Integer.parseInt(objectId)); query.setInteger("tableId", Integer.parseInt(tableId)); query.setParameterList( "filter", filter ); List<Note> noteList = query.list(); closeSession(); return noteList; }catch(HibernateException e){ handleException(e, "getNotesChronologicallyByRefIdAndRefTable"); } return null; } @Override public List<Note> getNotesInDateRangeAndType( Date lowDate, Date highDate, String noteType, String referenceTableId ) throws LIMSRuntimeException{ String sql = "FROM Note n where n.noteType = :type and n.referenceTableId = :referenceTableId and n.lastupdated between :lowDate and :highDate"; try{ Query query = HibernateUtil.getSession().createQuery(sql); query.setString( "type", noteType ); query.setInteger( "referenceTableId", Integer.parseInt(referenceTableId )); query.setDate( "lowDate", lowDate ); query.setDate( "highDate", highDate ); List<Note> noteList = query.list(); closeSession(); return noteList; }catch(HibernateException e){ handleException(e, "getNotesInDateRangeAndType"); } return null; } }
pfschwartz/openelisglobal-core
app/src/us/mn/state/health/lims/note/daoimpl/NoteDAOImpl.java
Java
mpl-2.0
15,977
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use audio_video_metadata; use document_loader::LoadType; use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; use dom::bindings::codegen::Bindings::HTMLMediaElementBinding::CanPlayTypeResult; use dom::bindings::codegen::Bindings::HTMLMediaElementBinding::HTMLMediaElementConstants::*; use dom::bindings::codegen::Bindings::HTMLMediaElementBinding::HTMLMediaElementMethods; use dom::bindings::codegen::Bindings::MediaErrorBinding::MediaErrorConstants::*; use dom::bindings::codegen::Bindings::MediaErrorBinding::MediaErrorMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::{MutNullableJS, Root}; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::DomObject; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::{Element, AttributeMutation}; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::htmlaudioelement::HTMLAudioElement; use dom::htmlelement::HTMLElement; use dom::htmlsourceelement::HTMLSourceElement; use dom::htmlvideoelement::HTMLVideoElement; use dom::mediaerror::MediaError; use dom::node::{window_from_node, document_from_node, Node, UnbindContext}; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use net_traits::{FetchResponseListener, FetchMetadata, Metadata, NetworkError}; use net_traits::request::{CredentialsMode, Destination, RequestInit, Type as RequestType}; use network_listener::{NetworkListener, PreInvoke}; use script_thread::{Runnable, ScriptThread}; use servo_atoms::Atom; use servo_url::ServoUrl; use std::cell::Cell; use std::sync::{Arc, Mutex}; use task_source::TaskSource; use time::{self, Timespec, Duration}; struct HTMLMediaElementContext { /// The element that initiated the request. elem: Trusted<HTMLMediaElement>, /// The response body received to date. data: Vec<u8>, /// The response metadata received to date. metadata: Option<Metadata>, /// The generation of the media element when this fetch started. generation_id: u32, /// Time of last progress notification. next_progress_event: Timespec, /// Url of resource requested. url: ServoUrl, /// Whether the media metadata has been completely received. have_metadata: bool, /// True if this response is invalid and should be ignored. ignore_response: bool, } impl FetchResponseListener for HTMLMediaElementContext { fn process_request_body(&mut self) {} fn process_request_eof(&mut self) {} // https://html.spec.whatwg.org/multipage/#media-data-processing-steps-list fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { self.metadata = metadata.ok().map(|m| { match m { FetchMetadata::Unfiltered(m) => m, FetchMetadata::Filtered { unsafe_, .. } => unsafe_ } }); // => "If the media data cannot be fetched at all..." let is_failure = self.metadata .as_ref() .and_then(|m| m.status .as_ref() .map(|&(s, _)| s < 200 || s >= 300)) .unwrap_or(false); if is_failure { // Ensure that the element doesn't receive any further notifications // of the aborted fetch. The dedicated failure steps will be executed // when response_complete runs. self.ignore_response = true; } } fn process_response_chunk(&mut self, mut payload: Vec<u8>) { if self.ignore_response { return; } self.data.append(&mut payload); let elem = self.elem.root(); // https://html.spec.whatwg.org/multipage/#media-data-processing-steps-list // => "Once enough of the media data has been fetched to determine the duration..." if !self.have_metadata { self.check_metadata(&elem); } else { elem.change_ready_state(HAVE_CURRENT_DATA); } // https://html.spec.whatwg.org/multipage/#concept-media-load-resource step 4, // => "If mode is remote" step 2 if time::get_time() > self.next_progress_event { elem.queue_fire_simple_event("progress"); self.next_progress_event = time::get_time() + Duration::milliseconds(350); } } // https://html.spec.whatwg.org/multipage/#media-data-processing-steps-list fn process_response_eof(&mut self, status: Result<(), NetworkError>) { let elem = self.elem.root(); // => "If the media data can be fetched but is found by inspection to be in an unsupported // format, or can otherwise not be rendered at all" if !self.have_metadata { elem.queue_dedicated_media_source_failure_steps(); } // => "Once the entire media resource has been fetched..." else if status.is_ok() { elem.change_ready_state(HAVE_ENOUGH_DATA); elem.fire_simple_event("progress"); elem.network_state.set(NETWORK_IDLE); elem.fire_simple_event("suspend"); } // => "If the connection is interrupted after some media data has been received..." else if elem.ready_state.get() != HAVE_NOTHING { // Step 2 elem.error.set(Some(&*MediaError::new(&*window_from_node(&*elem), MEDIA_ERR_NETWORK))); // Step 3 elem.network_state.set(NETWORK_IDLE); // TODO: Step 4 - update delay load flag // Step 5 elem.fire_simple_event("error"); } else { // => "If the media data cannot be fetched at all..." elem.queue_dedicated_media_source_failure_steps(); } let document = document_from_node(&*elem); document.finish_load(LoadType::Media(self.url.clone())); } } impl PreInvoke for HTMLMediaElementContext { fn should_invoke(&self) -> bool { //TODO: finish_load needs to run at some point if the generation changes. self.elem.root().generation_id.get() == self.generation_id } } impl HTMLMediaElementContext { fn new(elem: &HTMLMediaElement, url: ServoUrl) -> HTMLMediaElementContext { HTMLMediaElementContext { elem: Trusted::new(elem), data: vec![], metadata: None, generation_id: elem.generation_id.get(), next_progress_event: time::get_time() + Duration::milliseconds(350), url: url, have_metadata: false, ignore_response: false, } } fn check_metadata(&mut self, elem: &HTMLMediaElement) { match audio_video_metadata::get_format_from_slice(&self.data) { Ok(audio_video_metadata::Metadata::Video(meta)) => { let dur = meta.audio.duration.unwrap_or(::std::time::Duration::new(0, 0)); *elem.video.borrow_mut() = Some(VideoMedia { format: format!("{:?}", meta.format), duration: Duration::seconds(dur.as_secs() as i64) + Duration::nanoseconds(dur.subsec_nanos() as i64), width: meta.dimensions.width, height: meta.dimensions.height, video: meta.video.unwrap_or("".to_owned()), audio: meta.audio.audio, }); // Step 6 elem.change_ready_state(HAVE_METADATA); self.have_metadata = true; } _ => {} } } } #[derive(JSTraceable, HeapSizeOf)] pub struct VideoMedia { format: String, #[ignore_heap_size_of = "defined in time"] duration: Duration, width: u32, height: u32, video: String, audio: Option<String>, } #[dom_struct] pub struct HTMLMediaElement { htmlelement: HTMLElement, network_state: Cell<u16>, ready_state: Cell<u16>, current_src: DOMRefCell<String>, generation_id: Cell<u32>, first_data_load: Cell<bool>, error: MutNullableJS<MediaError>, paused: Cell<bool>, autoplaying: Cell<bool>, video: DOMRefCell<Option<VideoMedia>>, } impl HTMLMediaElement { pub fn new_inherited(tag_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLMediaElement { HTMLMediaElement { htmlelement: HTMLElement::new_inherited(tag_name, prefix, document), network_state: Cell::new(NETWORK_EMPTY), ready_state: Cell::new(HAVE_NOTHING), current_src: DOMRefCell::new("".to_owned()), generation_id: Cell::new(0), first_data_load: Cell::new(true), error: Default::default(), paused: Cell::new(true), autoplaying: Cell::new(true), video: DOMRefCell::new(None), } } // https://html.spec.whatwg.org/multipage/#internal-pause-steps fn internal_pause_steps(&self) { // Step 1 self.autoplaying.set(false); // Step 2 if !self.Paused() { // 2.1 self.paused.set(true); // 2.2 self.queue_internal_pause_steps_task(); // TODO 2.3 (official playback position) } // TODO step 3 (media controller) } // https://html.spec.whatwg.org/multipage/#notify-about-playing fn notify_about_playing(&self) { // Step 1 self.fire_simple_event("playing"); // TODO Step 2 } fn queue_notify_about_playing(&self) { struct Task { elem: Trusted<HTMLMediaElement>, } impl Runnable for Task { fn handler(self: Box<Task>) { self.elem.root().notify_about_playing(); } } let task = box Task { elem: Trusted::new(self), }; let win = window_from_node(self); let _ = win.dom_manipulation_task_source().queue(task, win.upcast()); } // https://html.spec.whatwg.org/multipage/#internal-pause-steps step 2.2 fn queue_internal_pause_steps_task(&self) { struct Task { elem: Trusted<HTMLMediaElement>, } impl Runnable for Task { fn handler(self: Box<Task>) { let elem = self.elem.root(); // 2.2.1 elem.fire_simple_event("timeupdate"); // 2.2.2 elem.fire_simple_event("pause"); // TODO 2.2.3 } } let task = box Task { elem: Trusted::new(self), }; let win = window_from_node(self); let _ = win.dom_manipulation_task_source().queue(task, win.upcast()); } fn queue_fire_simple_event(&self, type_: &'static str) { let win = window_from_node(self); let task = box FireSimpleEventTask::new(self, type_); let _ = win.dom_manipulation_task_source().queue(task, win.upcast()); } fn fire_simple_event(&self, type_: &str) { let window = window_from_node(self); let event = Event::new(window.upcast(), Atom::from(type_), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable); event.fire(self.upcast()); } // https://html.spec.whatwg.org/multipage/#ready-states fn change_ready_state(&self, ready_state: u16) { let old_ready_state = self.ready_state.get(); self.ready_state.set(ready_state); if self.network_state.get() == NETWORK_EMPTY { return; } // Step 1 match (old_ready_state, ready_state) { // previous ready state was HAVE_NOTHING, and the new ready state is // HAVE_METADATA (HAVE_NOTHING, HAVE_METADATA) => { self.queue_fire_simple_event("loadedmetadata"); } // previous ready state was HAVE_METADATA and the new ready state is // HAVE_CURRENT_DATA or greater (HAVE_METADATA, HAVE_CURRENT_DATA) | (HAVE_METADATA, HAVE_FUTURE_DATA) | (HAVE_METADATA, HAVE_ENOUGH_DATA) => { if self.first_data_load.get() { self.first_data_load.set(false); self.queue_fire_simple_event("loadeddata"); } } // previous ready state was HAVE_FUTURE_DATA or more, and the new ready // state is HAVE_CURRENT_DATA or less (HAVE_FUTURE_DATA, HAVE_CURRENT_DATA) | (HAVE_ENOUGH_DATA, HAVE_CURRENT_DATA) | (HAVE_FUTURE_DATA, HAVE_METADATA) | (HAVE_ENOUGH_DATA, HAVE_METADATA) | (HAVE_FUTURE_DATA, HAVE_NOTHING) | (HAVE_ENOUGH_DATA, HAVE_NOTHING) => { // TODO: timeupdate event logic + waiting } _ => (), } // Step 1 // If the new ready state is HAVE_FUTURE_DATA or HAVE_ENOUGH_DATA, // then the relevant steps below must then be run also. match (old_ready_state, ready_state) { // previous ready state was HAVE_CURRENT_DATA or less, and the new ready // state is HAVE_FUTURE_DATA (HAVE_CURRENT_DATA, HAVE_FUTURE_DATA) | (HAVE_METADATA, HAVE_FUTURE_DATA) | (HAVE_NOTHING, HAVE_FUTURE_DATA) => { self.queue_fire_simple_event("canplay"); if !self.Paused() { self.queue_notify_about_playing(); } } // new ready state is HAVE_ENOUGH_DATA (_, HAVE_ENOUGH_DATA) => { if old_ready_state <= HAVE_CURRENT_DATA { self.queue_fire_simple_event("canplay"); if !self.Paused() { self.queue_notify_about_playing(); } } //TODO: check sandboxed automatic features browsing context flag if self.autoplaying.get() && self.Paused() && self.Autoplay() { // Step 1 self.paused.set(false); // TODO step 2: show poster // Step 3 self.queue_fire_simple_event("play"); // Step 4 self.queue_notify_about_playing(); // Step 5 self.autoplaying.set(false); } self.queue_fire_simple_event("canplaythrough"); } _ => (), } // TODO Step 2: media controller } // https://html.spec.whatwg.org/multipage/#concept-media-load-algorithm fn invoke_resource_selection_algorithm(&self) { // Step 1 self.network_state.set(NETWORK_NO_SOURCE); // TODO step 2 (show poster) // TODO step 3 (delay load event) // Step 4 let doc = document_from_node(self); ScriptThread::await_stable_state(ResourceSelectionTask::new(self, doc.base_url())); } // https://html.spec.whatwg.org/multipage/#concept-media-load-algorithm #[allow(unreachable_code)] fn resource_selection_algorithm_sync(&self, base_url: ServoUrl) { // TODO step 5 (populate pending text tracks) // Step 6 let mode = if false { // TODO media provider object ResourceSelectionMode::Object } else if let Some(attr) = self.upcast::<Element>().get_attribute(&ns!(), &local_name!("src")) { ResourceSelectionMode::Attribute(attr.Value().to_string()) } else if false { // TODO: when implementing this remove #[allow(unreachable_code)] above. // TODO <source> child ResourceSelectionMode::Children(panic!()) } else { self.network_state.set(NETWORK_EMPTY); return; }; // Step 7 self.network_state.set(NETWORK_LOADING); // Step 8 self.queue_fire_simple_event("loadstart"); // Step 9 match mode { ResourceSelectionMode::Object => { // Step 1 *self.current_src.borrow_mut() = "".to_owned(); // Step 4 self.resource_fetch_algorithm(Resource::Object); } ResourceSelectionMode::Attribute(src) => { // Step 1 if src.is_empty() { self.queue_dedicated_media_source_failure_steps(); return; } // Step 2 let absolute_url = base_url.join(&src).map_err(|_| ()); // Step 3 if let Ok(url) = absolute_url { *self.current_src.borrow_mut() = url.as_str().into(); // Step 4 self.resource_fetch_algorithm(Resource::Url(url)); } else { self.queue_dedicated_media_source_failure_steps(); } } ResourceSelectionMode::Children(_child) => { // TODO self.queue_dedicated_media_source_failure_steps() } } } // https://html.spec.whatwg.org/multipage/#concept-media-load-resource fn resource_fetch_algorithm(&self, resource: Resource) { // TODO step 3 (remove text tracks) // Step 4 if let Resource::Url(url) = resource { // 4.1 if self.Preload() == "none" && !self.autoplaying.get() { // 4.1.1 self.network_state.set(NETWORK_IDLE); // 4.1.2 self.queue_fire_simple_event("suspend"); // TODO 4.1.3 (delay load flag) // TODO 4.1.5-7 (state for load that initiates later) return; } // 4.2 let context = Arc::new(Mutex::new(HTMLMediaElementContext::new(self, url.clone()))); let (action_sender, action_receiver) = ipc::channel().unwrap(); let window = window_from_node(self); let listener = NetworkListener { context: context, task_source: window.networking_task_source(), wrapper: Some(window.get_runnable_wrapper()) }; ROUTER.add_route(action_receiver.to_opaque(), box move |message| { listener.notify_fetch(message.to().unwrap()); }); // FIXME: we're supposed to block the load event much earlier than now let document = document_from_node(self); let ty = if self.is::<HTMLAudioElement>() { RequestType::Audio } else if self.is::<HTMLVideoElement>() { RequestType::Video } else { unreachable!("Unexpected HTMLMediaElement") }; let request = RequestInit { url: url.clone(), type_: ty, destination: Destination::Media, credentials_mode: CredentialsMode::Include, use_url_credentials: true, origin: document.url(), pipeline_id: Some(self.global().pipeline_id()), referrer_url: Some(document.url()), referrer_policy: document.get_referrer_policy(), .. RequestInit::default() }; document.fetch_async(LoadType::Media(url), request, action_sender); } else { // TODO local resource fetch self.queue_dedicated_media_source_failure_steps(); } } fn queue_dedicated_media_source_failure_steps(&self) { let window = window_from_node(self); let _ = window.dom_manipulation_task_source().queue( box DedicatedMediaSourceFailureTask::new(self), window.upcast()); } // https://html.spec.whatwg.org/multipage/#dedicated-media-source-failure-steps fn dedicated_media_source_failure(&self) { // Step 1 self.error.set(Some(&*MediaError::new(&*window_from_node(self), MEDIA_ERR_SRC_NOT_SUPPORTED))); // TODO step 2 (forget resource tracks) // Step 3 self.network_state.set(NETWORK_NO_SOURCE); // TODO step 4 (show poster) // Step 5 self.fire_simple_event("error"); // TODO step 6 (resolve pending play promises) // TODO step 7 (delay load event) } // https://html.spec.whatwg.org/multipage/#media-element-load-algorithm fn media_element_load_algorithm(&self) { self.first_data_load.set(true); // TODO Step 1 (abort resource selection algorithm instances) // Step 2 self.generation_id.set(self.generation_id.get() + 1); // TODO reject pending play promises // Step 3 let network_state = self.NetworkState(); if network_state == NETWORK_LOADING || network_state == NETWORK_IDLE { self.queue_fire_simple_event("abort"); } // Step 4 if network_state != NETWORK_EMPTY { // 4.1 self.queue_fire_simple_event("emptied"); // TODO 4.2 (abort in-progress fetch) // TODO 4.3 (detach media provider object) // TODO 4.4 (forget resource tracks) // 4.5 if self.ready_state.get() != HAVE_NOTHING { self.change_ready_state(HAVE_NOTHING); } // 4.6 if !self.Paused() { self.paused.set(true); } // TODO 4.7 (seeking) // TODO 4.8 (playback position) // TODO 4.9 (timeline offset) // TODO 4.10 (duration) } // TODO step 5 (playback rate) // Step 6 self.error.set(None); self.autoplaying.set(true); // Step 7 self.invoke_resource_selection_algorithm(); // TODO step 8 (stop previously playing resource) } } impl HTMLMediaElementMethods for HTMLMediaElement { // https://html.spec.whatwg.org/multipage/#dom-media-networkstate fn NetworkState(&self) -> u16 { self.network_state.get() } // https://html.spec.whatwg.org/multipage/#dom-media-readystate fn ReadyState(&self) -> u16 { self.ready_state.get() } // https://html.spec.whatwg.org/multipage/#dom-media-autoplay make_bool_getter!(Autoplay, "autoplay"); // https://html.spec.whatwg.org/multipage/#dom-media-autoplay make_bool_setter!(SetAutoplay, "autoplay"); // https://html.spec.whatwg.org/multipage/#dom-media-src make_url_getter!(Src, "src"); // https://html.spec.whatwg.org/multipage/#dom-media-src make_setter!(SetSrc, "src"); // https://html.spec.whatwg.org/multipage/#attr-media-preload // Missing value default is user-agent defined. make_enumerated_getter!(Preload, "preload", "", "none" | "metadata" | "auto"); // https://html.spec.whatwg.org/multipage/#attr-media-preload make_setter!(SetPreload, "preload"); // https://html.spec.whatwg.org/multipage/#dom-media-currentsrc fn CurrentSrc(&self) -> DOMString { DOMString::from(self.current_src.borrow().clone()) } // https://html.spec.whatwg.org/multipage/#dom-media-load fn Load(&self) { self.media_element_load_algorithm(); } // https://html.spec.whatwg.org/multipage/#dom-navigator-canplaytype fn CanPlayType(&self, _type_: DOMString) -> CanPlayTypeResult { // TODO: application/octet-stream CanPlayTypeResult::Maybe } // https://html.spec.whatwg.org/multipage/#dom-media-error fn GetError(&self) -> Option<Root<MediaError>> { self.error.get() } // https://html.spec.whatwg.org/multipage/#dom-media-play fn Play(&self) { // TODO step 1 // Step 2 if self.error.get().map_or(false, |e| e.Code() == MEDIA_ERR_SRC_NOT_SUPPORTED) { // TODO return rejected promise return; } // TODO step 3 // Step 4 if self.network_state.get() == NETWORK_EMPTY { self.invoke_resource_selection_algorithm(); } // TODO step 5 (seek backwards) // TODO step 6 (media controller) let state = self.ready_state.get(); // Step 7 if self.Paused() { // 7.1 self.paused.set(false); // TODO 7.2 (show poster) // 7.3 self.queue_fire_simple_event("play"); // 7.4 if state == HAVE_NOTHING || state == HAVE_METADATA || state == HAVE_CURRENT_DATA { self.queue_fire_simple_event("waiting"); } else { self.queue_notify_about_playing(); } } // Step 8 else if state == HAVE_FUTURE_DATA || state == HAVE_ENOUGH_DATA { // TODO resolve pending play promises } // Step 9 self.autoplaying.set(false); // TODO step 10 (media controller) // TODO return promise } // https://html.spec.whatwg.org/multipage/#dom-media-pause fn Pause(&self) { // Step 1 if self.network_state.get() == NETWORK_EMPTY { self.invoke_resource_selection_algorithm(); } // Step 2 self.internal_pause_steps(); } // https://html.spec.whatwg.org/multipage/#dom-media-paused fn Paused(&self) -> bool { self.paused.get() } } impl VirtualMethods for HTMLMediaElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { &local_name!("src") => { if mutation.new_value(attr).is_some() { self.media_element_load_algorithm(); } } _ => (), }; } // https://html.spec.whatwg.org/multipage/#playing-the-media-resource:remove-an-element-from-a-document fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); if context.tree_in_doc { ScriptThread::await_stable_state(PauseIfNotInDocumentTask::new(self)); } } } struct FireSimpleEventTask { elem: Trusted<HTMLMediaElement>, type_: &'static str, } impl FireSimpleEventTask { fn new(target: &HTMLMediaElement, type_: &'static str) -> FireSimpleEventTask { FireSimpleEventTask { elem: Trusted::new(target), type_: type_, } } } impl Runnable for FireSimpleEventTask { fn name(&self) -> &'static str { "FireSimpleEventTask" } fn handler(self: Box<FireSimpleEventTask>) { let elem = self.elem.root(); elem.fire_simple_event(self.type_); } } struct ResourceSelectionTask { elem: Trusted<HTMLMediaElement>, base_url: ServoUrl, } impl ResourceSelectionTask { fn new(elem: &HTMLMediaElement, url: ServoUrl) -> ResourceSelectionTask { ResourceSelectionTask { elem: Trusted::new(elem), base_url: url, } } } impl Runnable for ResourceSelectionTask { fn name(&self) -> &'static str { "ResourceSelectionTask" } fn handler(self: Box<ResourceSelectionTask>) { self.elem.root().resource_selection_algorithm_sync(self.base_url); } } struct DedicatedMediaSourceFailureTask { elem: Trusted<HTMLMediaElement>, } impl DedicatedMediaSourceFailureTask { fn new(elem: &HTMLMediaElement) -> DedicatedMediaSourceFailureTask { DedicatedMediaSourceFailureTask { elem: Trusted::new(elem), } } } impl Runnable for DedicatedMediaSourceFailureTask { fn name(&self) -> &'static str { "DedicatedMediaSourceFailureTask" } fn handler(self: Box<DedicatedMediaSourceFailureTask>) { self.elem.root().dedicated_media_source_failure(); } } struct PauseIfNotInDocumentTask { elem: Trusted<HTMLMediaElement>, } impl PauseIfNotInDocumentTask { fn new(elem: &HTMLMediaElement) -> PauseIfNotInDocumentTask { PauseIfNotInDocumentTask { elem: Trusted::new(elem), } } } impl Runnable for PauseIfNotInDocumentTask { fn name(&self) -> &'static str { "PauseIfNotInDocumentTask" } fn handler(self: Box<PauseIfNotInDocumentTask>) { let elem = self.elem.root(); if !elem.upcast::<Node>().is_in_doc() { elem.internal_pause_steps(); } } } enum ResourceSelectionMode { Object, Attribute(String), Children(Root<HTMLSourceElement>), } enum Resource { Object, Url(ServoUrl), }
alajara/servo
components/script/dom/htmlmediaelement.rs
Rust
mpl-2.0
29,484
body { font-family: 'Segoe UI', sans-serif; margin: 0; overflow-y: scroll; } header { background-color: #0f1126; color: white; position: relative; } header a { color: white; } header h1 { margin: 0; padding: 0.25em 0; } #main { margin: 10px; } .version { border-top: 1px dotted gray; padding: 10px; clear: both; } .buttons { float: right; } .buttons > .button { display: block; } .buttons > .not-compatible { color: gray; font-size: 70%; max-width: 180px; text-align: center; } .button { display: inline-block; border: 0; border-radius: 5px; padding: 5px 10px; border: 1px solid transparent; text-decoration: none; text-align: center; background-color: royalblue; color: white; } .button:empty { display: none; } .button.install { background-color: green; } .button.download { border-color: royalblue; background-color: white; color: royalblue; font-size: 80%; } .button.install::before { content: '+'; font-size: 200%; font-weight: bold; line-height: 50%; vertical-align: top; } .button.download::before { content: '\2B73'; font-size: 150%; font-weight: bold; line-height: 100%; vertical-align: top; } .button.prev::before { content: '\2190'; font-size: 200%; font-weight: bold; line-height: 50%; vertical-align: top; } .button.next::after { content: '\2192'; font-size: 200%; font-weight: bold; line-height: 50%; vertical-align: top; } .button:not(:first-child) { margin-top: 5px; } .version-header { font-size: 125%; font-weight: bold; } .version-header .tags > * { background-color: blue; color: white; border-radius: 5px; padding: 1px 5px; font-size: 60%; vertical-align: bottom; line-height: 200%; } .version-header .tags > :empty { display: none; } .released, .compatibility, .license { color: gray; font-size: 70%; } .release_notes:not(:empty) { margin-top: 10px; font-size: 80%; white-space: pre-wrap; } footer { text-align: center; border-top: 1px dotted gray; font-size: 80%; }
lemon-juice/AMO-Browsing-for-SeaMonkey
xpi-versions/main.css
CSS
mpl-2.0
2,490
/* The following code is the modified part of the libxml * available at http://xmlsoft.org * under the terms of the MIT License * http://opensource.org/licenses/mit-license.html */ /* * Summary: Provide Canonical XML and Exclusive XML Canonicalization * Description: the c14n modules provides a * * "Canonical XML" implementation * http://www.w3.org/TR/xml-c14n * * and an * * "Exclusive XML Canonicalization" implementation * http://www.w3.org/TR/xml-exc-c14n * Copy: See Copyright for the status of this software. * * Author: Aleksey Sanin <aleksey@aleksey.com> */ #ifndef __XML_C14N_H__ #define __XML_C14N_H__ #ifdef LIBXML_C14N_ENABLED #ifdef LIBXML_OUTPUT_ENABLED #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include "xmlversion.h" #include "tree.h" #include "xpath.h" /* * XML Canonicazation * http://www.w3.org/TR/xml-c14n * * Exclusive XML Canonicazation * http://www.w3.org/TR/xml-exc-c14n * * Canonical form of an XML document could be created if and only if * a) default attributes (if any) are added to all nodes * b) all character and parsed entity references are resolved * In order to achive this in libxml2 the document MUST be loaded with * following global setings: * * xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS; * xmlSubstituteEntitiesDefault(1); * * or corresponding parser context setting: * xmlParserCtxtPtr ctxt; * * ... * ctxt->loadsubset = XML_DETECT_IDS | XML_COMPLETE_ATTRS; * ctxt->replaceEntities = 1; * ... */ XMLPUBFUN int XMLCALL xmlC14NDocSaveTo (xmlDocPtr doc, xmlNodeSetPtr nodes, int exclusive, xmlChar **inclusive_ns_prefixes, int with_comments, xmlOutputBufferPtr buf); XMLPUBFUN int XMLCALL xmlC14NDocDumpMemory (xmlDocPtr doc, xmlNodeSetPtr nodes, int exclusive, xmlChar **inclusive_ns_prefixes, int with_comments, xmlChar **doc_txt_ptr); XMLPUBFUN int XMLCALL xmlC14NDocSave (xmlDocPtr doc, xmlNodeSetPtr nodes, int exclusive, xmlChar **inclusive_ns_prefixes, int with_comments, const char* filename, int compression); /** * This is the core C14N function */ typedef int (*xmlC14NIsVisibleCallback) (void* user_data, xmlNodePtr node, xmlNodePtr parent); XMLPUBFUN int XMLCALL xmlC14NExecute (xmlDocPtr doc, xmlC14NIsVisibleCallback is_visible_callback, void* user_data, int exclusive, xmlChar **inclusive_ns_prefixes, int with_comments, xmlOutputBufferPtr buf); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* LIBXML_OUTPUT_ENABLED */ #endif /* LIBXML_C14N_ENABLED */ #endif /* __XML_C14N_H__ */
evilmucedin/tomita-parser
src/contrib/libs/libxml/include/libxml/c14n.h
C
mpl-2.0
2,746
define([ 'underscore', 'backbone', 'models/version' ], function(_, Backbone, VersionModel){ var VersionCollection = Backbone.Collection.extend({ model: VersionModel, parse: function(response) { return response.data.versions; }, healthClasses: { 'OK': { badge: 'badge-success', icon: 'icon-ok' }, 'WARNING': { badge: 'badge-warning', icon: 'icon-warning-sign' }, 'ERROR': { badge: 'badge-important', icon: 'icon-ban-circle' } }, comparator: function(version) { return -version.get("version"); } }); return VersionCollection; });
kaze/paasmaker
paasmaker/static/js/collections/versions.js
JavaScript
mpl-2.0
563
try: import traceback import argparse import textwrap import glob import os import logging import datetime import multiprocessing from libs import LasPyConverter except ImportError as err: print('Error {0} import module: {1}'.format(__name__, err)) traceback.print_exc() exit(128) script_path = __file__ header = textwrap.dedent('''LAS Diff''') class LasPyParameters: def __init__(self): # predefinied paths self.parser = argparse.ArgumentParser(prog="lasdiff", formatter_class=argparse.RawDescriptionHelpFormatter, description='', epilog=textwrap.dedent(''' example: ''')) # reguired parameters self.parser.add_argument('-i', type=str, dest='input', required=True, help='required: input file or folder') self.parser.add_argument('-o', type=str, dest='output', required=True, help='required: output file or folder (d:\lasfiles\\tests\\results)') # optional parameters self.parser.add_argument('-input_format', type=str, dest='input_format', required=False, choices=['las', 'laz'], help='optional: input format (default=las, laz is not implemented (yet))') self.parser.add_argument('-cores', type=int, dest='cores', required=False, default=1, help='optional: cores (default=1)') self.parser.add_argument('-v', dest='verbose', required=False, help='optional: verbose toggle (-v=on, nothing=off)', action='store_true') self.parser.add_argument('-version', action='version', version=self.parser.prog) def parse(self): self.args = self.parser.parse_args() ##defaults if self.args.verbose: self.args.verbose = ' -v' else: self.args.verbose = '' if self.args.input_format == None: self.args.input_format = 'las' if self.args.cores == None: self.args.cores = 1 # ---------PUBLIC METHODS-------------------- def get_output(self): return self.args.output def get_input(self): return self.args.input def get_input_format(self): return self.args.input_format def get_verbose(self): return self.args.verbose def get_cores(self): return self.args.cores def DiffLas(parameters): # Parse incoming parameters source_file = parameters[0] destination_file = parameters[1] # Get name for this process current = multiprocessing.current_proces() proc_name = current.name logging.info('[%s] Starting ...' % (proc_name)) logging.info( '[%s] Creating diff of %s LAS PointCloud file and %s LAS PointCloud file ...' % ( proc_name, source_file, destination_file)) # Opening source LAS files for read and write lasFiles = LasPyConverter.LasPyCompare(source_file, destination_file) # Opening destination LAS file logging.info('[%s] Opening %s LAS PointCloud file and %s LAS PointCloud file ...' % ( proc_name, source_file, destination_file)) lasFiles.OpenReanOnly() logging.info('[%s] Comparing %s LAS PointCloud file and %s LAS PointCloud file ...' % ( proc_name, source_file, destination_file)) lasFiles.ComparePointCloud() logging.info('[%s] Closing %s LAS PointCloud.' % (proc_name, destination_file)) lasFiles.Close() logging.info('[%s] %s LAS PointCloud has closed.' % (proc_name, destination_file)) return 0 def SetLogging(logfilename): logging.basicConfig( filename=logfilename, filemode='w', format='%(asctime)s %(name)s %(levelname)s %(message)s', datefmt='%d-%m-%Y %H:%M:%S', level=logging.DEBUG) # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() console.setLevel(logging.INFO) # set a format which is simpler for console use formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s', datefmt='%d-%m-%Y %H:%M:%S') # tell the handler to use this format console.setFormatter(formatter) # add the handler to the root logger logging.getLogger('').addHandler(console) def main(): logfilename = 'lasdiff_' + datetime.datetime.today().strftime('%Y%m%d_%H%M%S') + '.log' SetLogging(logfilename) logging.info(header) lasconverterworkflow = LasPyParameters() lasconverterworkflow.parse() # File/Directory handler inputfiles = lasconverterworkflow.get_input() inputformat = lasconverterworkflow.get_input_format() outputfiles = lasconverterworkflow.get_output() outputpath = os.path.normpath(outputfiles) cores = lasconverterworkflow.get_cores() inputisdir = False doing = [] if os.path.isdir(inputfiles): inputisdir = True inputfiles = glob.glob(os.path.join(inputfiles, '*' + inputformat)) if not os.path.exists(outputfiles): os.makedirs(outputfiles) for workfile in inputfiles: if os.path.isfile(workfile) and os.path.isfile(os.path.join(outputpath, os.path.basename(workfile))): logging.info('Adding %s to the queue.' % (workfile)) doing.append([workfile, os.path.join(outputpath, os.path.basename(workfile))]) else: logging.info('The %s is not file, or pair of comparable files. Skipping.' % (workfile)) elif os.path.isfile(inputfiles): inputisdir = False workfile = inputfiles if os.path.basename(outputfiles) is not "": doing.append([workfile, outputfiles]) else: doing.append([workfile, os.path.join(outputpath, os.path.basename(workfile))]) logging.info('Adding %s to the queue.' % (workfile)) else: # Not a file, not a dir logging.error('Cannot found input LAS PointCloud file: %s' % (inputfiles)) exit(1) # If we got one file, start only one process if inputisdir is False: cores = 1 if cores != 1: pool = multiprocessing.Pool(processes=cores) results = pool.map_async(DiffLas, doing) pool.close() pool.join() else: for d in doing: DiffLas(d) logging.info('Finished, exiting and go home ...') if __name__ == '__main__': main()
KAMI911/lactransformer
lactransformer/lasdiff.py
Python
mpl-2.0
6,565
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ /* File locked partial MAR file staged patch apply failure test */ const STATE_AFTER_STAGE = STATE_PENDING; function run_test() { if (!setupTestCommon()) { return; } gTestFiles = gTestFilesPartialSuccess; gTestDirs = gTestDirsPartialSuccess; setTestFilesAndDirsForFailure(); setupUpdaterTest(FILE_PARTIAL_MAR, false); } /** * Called after the call to setupUpdaterTest finishes. */ function setupUpdaterTestFinished() { runHelperLockFile(gTestFiles[2]); } /** * Called after the call to waitForHelperSleep finishes. */ function waitForHelperSleepFinished() { stageUpdate(); } /** * Called after the call to stageUpdate finishes. */ function stageUpdateFinished() { checkPostUpdateRunningFile(false); // Files aren't checked after staging since this test locks a file which // prevents reading the file. checkUpdateLogContains(ERR_ENSURE_COPY); // Switch the application to the staged application that was updated. runUpdate(STATE_FAILED_READ_ERROR, false, 1, false); } /** * Called after the call to runUpdate finishes. */ function runUpdateFinished() { waitForHelperExit(); } /** * Called after the call to waitForHelperExit finishes. */ function waitForHelperExitFinished() { standardInit(); Assert.equal(readStatusFile(), STATE_NONE, "the status file failure code" + MSG_SHOULD_EQUAL); Assert.equal(gUpdateManager.updateCount, 2, "the update manager updateCount attribute" + MSG_SHOULD_EQUAL); Assert.equal(gUpdateManager.getUpdateAt(0).state, STATE_FAILED, "the update state" + MSG_SHOULD_EQUAL); Assert.equal(gUpdateManager.getUpdateAt(0).errorCode, READ_ERROR, "the update errorCode" + MSG_SHOULD_EQUAL); checkPostUpdateRunningFile(false); checkFilesAfterUpdateFailure(getApplyDirFile); checkUpdateLogContains(ERR_UNABLE_OPEN_DEST); checkUpdateLogContains(STATE_FAILED_READ_ERROR + "\n" + CALL_QUIT); checkCallbackLog(); }
Yukarumya/Yukarum-Redfoxes
toolkit/mozapps/update/tests/unit_service_updater/marFileLockedStageFailurePartialSvc_win.js
JavaScript
mpl-2.0
2,069
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import mock import time import json from nose.tools import eq_, ok_, assert_raises from socorro.submitter.submitter_app import ( SubmitterApp, SubmitterFileSystemWalkerSource, ) from configman.dotdict import DotDict from socorro.external.crashstorage_base import Redactor from socorro.unittest.testbase import TestCase def sequencer(*args): list_of_args = list(args) def foo(*fargs, **fkwargs): try: return list_of_args.pop() except IndexError: return None return foo def generator_for_sequence(*args): list_of_args = list(args) def foo(*fargs, **fkwargs): try: yield list_of_args.pop() except IndexError: return return foo class TestSubmitterFileSystemWalkerSource(TestCase): def get_standard_config(self): config = DotDict() config.search_root = None config.dump_suffix = '.dump' config.dump_field = "upload_file_minidump" config.redactor_class = Redactor config.forbidden_keys = Redactor.required_config.forbidden_keys.default config.logger = mock.MagicMock() return config def test_setup(self): config = self.get_standard_config() sub_walker = SubmitterFileSystemWalkerSource(config) eq_(sub_walker.config, config) eq_(sub_walker.config.logger, config.logger) def test_get_raw_crash(self): config = self.get_standard_config() sub_walker = SubmitterFileSystemWalkerSource(config) raw = ('{"name":"Gabi", ''"submitted_timestamp":"%d"}' % time.time()) fake_raw_crash = DotDict(json.loads(raw)) mocked_get_raw_crash = mock.Mock(return_value=fake_raw_crash) sub_walker.get_raw_crash = mocked_get_raw_crash path_tuple = ['6611a662-e70f-4ba5-a397-69a3a2121129.dump', '6611a662-e70f-4ba5-a397-69a3a2121129.flash1.dump', '6611a662-e70f-4ba5-a397-69a3a2121129.flash2.dump', ] raw_crash = sub_walker.get_raw_crash(path_tuple) ok_(isinstance(raw_crash, DotDict)) eq_(raw_crash['name'], 'Gabi') def test_get_raw_dumps_as_files(self): config = self.get_standard_config() sub_walker = SubmitterFileSystemWalkerSource(config) dump_pathnames = ( '6611a662-e70f-4ba5-a397-69a3a2121129', ( 'raw_crash_file', '/some/path/6611a662-e70f-4ba5-a397-69a3a2121129.dump', '/some/path/6611a662-e70f-4ba5-a397-69a3a2121129.flash1.dump', '/some/path/6611a662-e70f-4ba5-a397-69a3a2121129.flash2.dump', ), ) raw_dumps_files = sub_walker.get_raw_dumps_as_files(dump_pathnames) dump_names = { 'upload_file_minidump': '/some/path/6611a662-e70f-4ba5-a397-69a3a2121129.dump', 'flash1': '/some/path/6611a662-e70f-4ba5-a397-69a3a2121129.flash1.dump', 'flash2': '/some/path/6611a662-e70f-4ba5-a397-69a3a2121129.flash2.dump' } ok_(isinstance(raw_dumps_files, dict)) eq_(raw_dumps_files, dump_names) def test_new_crashes(self): sequence = [ ( './', '6611a662-e70f-4ba5-a397-69a3a2121129.json', './6611a662-e70f-4ba5-a397-69a3a2121129.json', ), ( './', '6611a662-e70f-4ba5-a397-69a3a2121129.upload.dump', './6611a662-e70f-4ba5-a397-69a3a2121129.upload.dump', ), ( './', '7611a662-e70f-4ba5-a397-69a3a2121129.json', './7611a662-e70f-4ba5-a397-69a3a2121129.json', ), ( './', '7611a662-e70f-4ba5-a397-69a3a2121129.other.dump', './7611a662-e70f-4ba5-a397-69a3a2121129.other.dump', ), ( './', '7611a662-e70f-4ba5-a397-69a3a2121129.other.txt', './7611a662-e70f-4ba5-a397-69a3a2121129.other.txt', ), ( './', '8611a662-e70f-4ba5-a397-69a3a2121129.json', './8611a662-e70f-4ba5-a397-69a3a2121129.json', ) ] def findFileGenerator_mock_method(root, method): for x in sequence: if method(x): yield x def listdir_mock_method(a_path): for x in sequence: yield x[1] config = self.get_standard_config() expected = [ ( (( '6611a662-e70f-4ba5-a397-69a3a2121129', [ './6611a662-e70f-4ba5-a397-69a3a2121129.json', './6611a662-e70f-4ba5-a397-69a3a2121129.upload.dump' ], ), ), {} ), ( (( '7611a662-e70f-4ba5-a397-69a3a2121129', [ './7611a662-e70f-4ba5-a397-69a3a2121129.json', './7611a662-e70f-4ba5-a397-69a3a2121129.other.dump' ], ), ), {} ), ( (( '8611a662-e70f-4ba5-a397-69a3a2121129', [ './8611a662-e70f-4ba5-a397-69a3a2121129.json' ] ), ), {} ), ] find_patch_path = 'socorro.submitter.submitter_app.findFileGenerator' with mock.patch( find_patch_path, new_callable=lambda: findFileGenerator_mock_method ): listdir_patch_path = 'socorro.submitter.submitter_app.listdir' with mock.patch( listdir_patch_path, new_callable=lambda: listdir_mock_method ): sub_walker = SubmitterFileSystemWalkerSource(config) result = [x for x in sub_walker.new_crashes()] eq_(result, expected) class TestSubmitterApp(TestCase): def get_standard_config(self): config = DotDict() config.source = DotDict() mocked_source_crashstorage = mock.Mock() mocked_source_crashstorage.id = 'mocked_source_crashstorage' config.source.crashstorage_class = mock.Mock( return_value=mocked_source_crashstorage ) config.destination = DotDict() mocked_destination_crashstorage = mock.Mock() mocked_destination_crashstorage.id = 'mocked_destination_crashstorage' config.destination.crashstorage_class = mock.Mock( return_value=mocked_destination_crashstorage ) config.producer_consumer = DotDict() mocked_producer_consumer = mock.Mock() mocked_producer_consumer.id = 'mocked_producer_consumer' config.producer_consumer.producer_consumer_class = mock.Mock( return_value=mocked_producer_consumer ) config.producer_consumer.number_of_threads = float(1) config.new_crash_source = DotDict() config.new_crash_source.new_crash_source_class = None config.submitter = DotDict() config.submitter.delay = 0 config.submitter.dry_run = False config.number_of_submissions = "all" config.logger = mock.MagicMock() return config def get_new_crash_source_config(self): config = DotDict() config.source = DotDict() mocked_source_crashstorage = mock.Mock() mocked_source_crashstorage.id = 'mocked_source_crashstorage' config.source.crashstorage_class = mock.Mock( return_value=mocked_source_crashstorage ) config.destination = DotDict() mocked_destination_crashstorage = mock.Mock() mocked_destination_crashstorage.id = 'mocked_destination_crashstorage' config.destination.crashstorage_class = mock.Mock( return_value=mocked_destination_crashstorage ) config.producer_consumer = DotDict() mocked_producer_consumer = mock.Mock() mocked_producer_consumer.id = 'mocked_producer_consumer' config.producer_consumer.producer_consumer_class = mock.Mock( return_value=mocked_producer_consumer ) config.producer_consumer.number_of_threads = float(1) config.new_crash_source = DotDict() mocked_new_crash_source = mock.Mock() mocked_new_crash_source.id = 'mocked_new_crash_source' config.new_crash_source.new_crash_source_class = mock.Mock( return_value=mocked_new_crash_source ) config.submitter = DotDict() config.submitter.delay = 0 config.submitter.dry_run = False config.number_of_submissions = "all" config.logger = mock.MagicMock() return config def test_setup(self): config = self.get_standard_config() sub = SubmitterApp(config) eq_(sub.config, config) eq_(sub.config.logger, config.logger) def test_transform(self): config = self.get_standard_config() sub = SubmitterApp(config) sub._setup_source_and_destination() crash_id = '86b58ff2-9708-487d-bfc4-9dac32121214' fake_raw_crash = DotDict() mocked_get_raw_crash = mock.Mock(return_value=fake_raw_crash) sub.source.get_raw_crash = mocked_get_raw_crash fake_dump = {'upload_file_minidump': 'fake dump'} mocked_get_raw_dumps_as_files = mock.Mock(return_value=fake_dump) sub.source.get_raw_dumps_as_files = mocked_get_raw_dumps_as_files sub.destination.save_raw_crash = mock.Mock() sub.transform(crash_id) sub.source.get_raw_crash.assert_called_with(crash_id) sub.source.get_raw_dumps_as_files.assert_called_with(crash_id) sub.destination.save_raw_crash_with_file_dumps.assert_called_with( fake_raw_crash, fake_dump, crash_id ) def test_source_iterator(self): # Test with number of submissions equal to all # It raises StopIterations after all the elements were called config = self.get_standard_config() config.number_of_submissions = "all" sub = SubmitterApp(config) sub._setup_source_and_destination() sub._setup_task_manager() sub.source.new_crashes = lambda: iter([1, 2, 3]) itera = sub.source_iterator() eq_(itera.next(), ((1,), {})) eq_(itera.next(), ((2,), {})) eq_(itera.next(), ((3,), {})) assert_raises(StopIteration, itera.next) # Test with number of submissions equal to forever # It never raises StopIterations config = self.get_standard_config() config.number_of_submissions = "forever" sub = SubmitterApp(config) sub._setup_source_and_destination() sub._setup_task_manager() itera = sub.source_iterator() sub.source.new_crashes = lambda: iter([1, 2, 3]) eq_(itera.next(), ((1,), {})) eq_(itera.next(), ((2,), {})) eq_(itera.next(), ((3,), {})) eq_(itera.next(), ((1,), {})) eq_(itera.next(), ((2,), {})) eq_(itera.next(), ((3,), {})) # Test with number of submissions equal to an integer > number of items # It raises StopIterations after some number of elements were called config = self.get_standard_config() config.number_of_submissions = "5" sub = SubmitterApp(config) sub._setup_source_and_destination() sub._setup_task_manager() itera = sub.source_iterator() sub.source.new_crashes = lambda: iter([1, 2, 3]) eq_(itera.next(), ((1,), {})) eq_(itera.next(), ((2,), {})) eq_(itera.next(), ((3,), {})) eq_(itera.next(), ((1,), {})) eq_(itera.next(), ((2,), {})) assert_raises(StopIteration, itera.next) # Test with number of submissions equal to an integer < number of items # It raises StopIterations after some number of elements were called config = self.get_standard_config() config.number_of_submissions = "1" sub = SubmitterApp(config) sub._setup_source_and_destination() sub._setup_task_manager() itera = sub.source_iterator() sub.source.new_crashes = lambda: iter([1, 2, 3]) eq_(itera.next(), ((1,), {})) assert_raises(StopIteration, itera.next) def test_new_crash_source_iterator(self): # Test with number of submissions equal to all # It raises StopIterations after all the elements were called config = self.get_new_crash_source_config() config.number_of_submissions = "all" sub = SubmitterApp(config) sub._setup_source_and_destination() sub._setup_task_manager() config.new_crash_source.new_crash_source_class.return_value \ .new_crashes = lambda: iter([1, 2, 3]) itera = sub.source_iterator() eq_(itera.next(), ((1,), {})) eq_(itera.next(), ((2,), {})) eq_(itera.next(), ((3,), {})) assert_raises(StopIteration, itera.next) # Test with number of submissions equal to forever # It never raises StopIterations config = self.get_new_crash_source_config() config.number_of_submissions = "forever" sub = SubmitterApp(config) sub._setup_source_and_destination() sub._setup_task_manager() itera = sub.source_iterator() # setup a fake iter using two form of the data to ensure it deals # with both forms correctly. config.new_crash_source.new_crash_source_class.return_value \ .new_crashes = lambda: iter([1, ((2, ), {}), 3]) eq_(itera.next(), ((1,), {})) eq_(itera.next(), ((2,), {})) eq_(itera.next(), ((3,), {})) eq_(itera.next(), ((1,), {})) eq_(itera.next(), ((2,), {})) eq_(itera.next(), ((3,), {})) # Test with number of submissions equal to an integer > number of items # It raises StopIterations after some number of elements were called config = self.get_new_crash_source_config() config.number_of_submissions = "5" sub = SubmitterApp(config) sub._setup_source_and_destination() sub._setup_task_manager() itera = sub.source_iterator() def _iter(): return iter([((1, ), {'finished_func': (1,)}), 2, 3]) config.new_crash_source.new_crash_source_class.return_value.new_crashes = _iter eq_(itera.next(), ((1,), {'finished_func': (1,)})) eq_(itera.next(), ((2,), {})) eq_(itera.next(), ((3,), {})) eq_(itera.next(), ((1,), {'finished_func': (1,)})) eq_(itera.next(), ((2,), {})) assert_raises(StopIteration, itera.next) # Test with number of submissions equal to an integer < number of items # It raises StopIterations after some number of elements were called config = self.get_new_crash_source_config() config.number_of_submissions = "1" sub = SubmitterApp(config) sub._setup_source_and_destination() sub._setup_task_manager() itera = sub.source_iterator() config.new_crash_source.new_crash_source_class.return_value \ .new_crashes = lambda: iter([1, 2, 3]) eq_(itera.next(), ((1,), {})) assert_raises(StopIteration, itera.next) # Test with number of submissions equal to an integer < number of items # AND the new_crashes iter returning an args, kwargs form rather than # than a crash_id # It raises StopIterations after some number of elements were called config = self.get_new_crash_source_config() config.number_of_submissions = "2" sub = SubmitterApp(config) sub._setup_source_and_destination() sub._setup_task_manager() itera = sub.source_iterator() config.new_crash_source.new_crash_source_class.return_value \ .new_crashes = lambda: iter( [ (((1, ['./1.json', './1.dump', './1.other.dump']), ), {}), (((2, ['./2.json', './1.dump']), ), {}) ] ) eq_( itera.next(), (((1, ['./1.json', './1.dump', './1.other.dump']), ), {}) ) eq_( itera.next(), (((2, ['./2.json', './1.dump']), ), {}) ) assert_raises(StopIteration, itera.next)
adngdb/socorro
socorro/unittest/submitter/test_submitter_app.py
Python
mpl-2.0
16,936
/* NUI3 - C++ cross-platform GUI framework for OpenGL based applications Copyright (C) 2002-2003 Sebastien Metrot licence: see nui3/LICENCE.TXT */ #pragma once #include "nui.h" #include "nuiContainer.h" class nuiSimpleContainer : public nuiContainer { public: nuiSimpleContainer(); virtual ~nuiSimpleContainer(); virtual bool SetObjectClass(const nglString& rName); virtual void SetObjectName(const nglString& rName); virtual bool AddChild(nuiWidgetPtr pChild); virtual bool DelChild(nuiWidgetPtr pChild); ///< Remove this child from the object. If Delete is true then the child will be deleted too. Returns true if success. virtual int GetChildrenCount() const; virtual nuiWidgetPtr GetChild(int index); virtual nuiWidgetPtr GetChild(nuiSize X, nuiSize Y); virtual nuiWidgetPtr GetChild(const nglString& rName, bool ResolveNameAsPath = true); ///< Find a child by its name property. Try to resolve path names like /window/fixed/toto or ../../tata if deepsearch is true virtual bool Clear(); virtual nuiContainer::Iterator* GetFirstChild(bool DoRefCounting = false); virtual nuiContainer::ConstIterator* GetFirstChild(bool DoRefCounting = false) const; virtual nuiContainer::Iterator* GetLastChild(bool DoRefCounting = false); virtual nuiContainer::ConstIterator* GetLastChild(bool DoRefCounting = false) const; virtual bool GetNextChild(nuiContainer::IteratorPtr pIterator); virtual bool GetNextChild(nuiContainer::ConstIteratorPtr pIterator) const; virtual bool GetPreviousChild(nuiContainer::IteratorPtr pIterator); virtual bool GetPreviousChild(nuiContainer::ConstIteratorPtr pIterator) const; virtual void RaiseChild(nuiWidgetPtr pChild); virtual void LowerChild(nuiWidgetPtr pChild); virtual void RaiseChildToFront(nuiWidgetPtr pChild); virtual void LowerChildToBack(nuiWidgetPtr pChild); protected: nuiWidgetList mpChildren; };
libnui/nui3
include/nuiSimpleContainer.h
C
mpl-2.0
1,914
/*! Theme: Black Metal (Bathory) Author: metalelf0 (https://github.com/metalelf0) License: ~ MIT (or more permissive) [via base16-schemes-source] Maintainer: @highlightjs/core-team Version: 2021.05.0 */ /* WARNING: DO NOT EDIT THIS FILE DIRECTLY. This theme file was auto-generated from the Base16 scheme black-metal-bathory by the Highlight.js Base16 template builder. - https://github.com/highlightjs/base16-highlightjs */ /* base00 #000000 Default Background base01 #121212 Lighter Background (Used for status bars, line number and folding marks) base02 #222222 Selection Background base03 #333333 Comments, Invisibles, Line Highlighting base04 #999999 Dark Foreground (Used for status bars) base05 #c1c1c1 Default Foreground, Caret, Delimiters, Operators base06 #999999 Light Foreground (Not often used) base07 #c1c1c1 Light Background (Not often used) base08 #5f8787 Variables, XML Tags, Markup Link Text, Markup Lists, Diff Deleted base09 #aaaaaa Integers, Boolean, Constants, XML Attributes, Markup Link Url base0A #e78a53 Classes, Markup Bold, Search Text Background base0B #fbcb97 Strings, Inherited Class, Markup Code, Diff Inserted base0C #aaaaaa Support, Regular Expressions, Escape Characters, Markup Quotes base0D #888888 Functions, Methods, Attribute IDs, Headings base0E #999999 Keywords, Storage, Selector, Markup Italic, Diff Changed base0F #444444 Deprecated, Opening/Closing Embedded Language Tags, e.g. <?php ?> */ pre code.hljs { display: block; overflow-x: auto; padding: 1em; } code.hljs { padding: 3px 5px; } .hljs { color: #c1c1c1; background: #000000; } .hljs ::selection { color: #222222; } /* purposely do not highlight these things */ .hljs-formula, .hljs-params, .hljs-property {} /* base03 - #333333 - Comments, Invisibles, Line Highlighting */ .hljs-comment { color: #333333; } /* base04 - #999999 - Dark Foreground (Used for status bars) */ .hljs-tag { color: #999999; } /* base05 - #c1c1c1 - Default Foreground, Caret, Delimiters, Operators */ .hljs-subst, .hljs-punctuation, .hljs-operator { color: #c1c1c1; } .hljs-operator { opacity: 0.7; } /* base08 - Variables, XML Tags, Markup Link Text, Markup Lists, Diff Deleted */ .hljs-bullet, .hljs-variable, .hljs-template-variable, .hljs-selector-tag, .hljs-name, .hljs-deletion { color: #5f8787; } /* base09 - Integers, Boolean, Constants, XML Attributes, Markup Link Url */ .hljs-symbol, .hljs-number, .hljs-link, .hljs-attr, .hljs-variable.constant_, .hljs-literal { color: #aaaaaa; } /* base0A - Classes, Markup Bold, Search Text Background */ .hljs-title, .hljs-class .hljs-title, .hljs-title.class_ { color: #e78a53; } .hljs-strong { font-weight:bold; color: #e78a53; } /* base0B - Strings, Inherited Class, Markup Code, Diff Inserted */ .hljs-code, .hljs-addition, .hljs-title.class_.inherited__, .hljs-string { color: #fbcb97; } /* base0C - Support, Regular Expressions, Escape Characters, Markup Quotes */ .hljs-built_in, .hljs-doctag, /* guessing */ .hljs-quote, .hljs-keyword.hljs-atrule, .hljs-regexp { color: #aaaaaa; } /* base0D - Functions, Methods, Attribute IDs, Headings */ .hljs-function .hljs-title, .hljs-attribute, .ruby .hljs-property, .hljs-title.function_, .hljs-section { color: #888888; } /* base0E - Keywords, Storage, Selector, Markup Italic, Diff Changed */ .hljs-type, /* .hljs-selector-id, */ /* .hljs-selector-class, */ /* .hljs-selector-attr, */ /* .hljs-selector-pseudo, */ .hljs-template-tag, .diff .hljs-meta, .hljs-keyword { color: #999999; } .hljs-emphasis { color: #999999; font-style: italic; } /* base0F - Deprecated, Opening/Closing Embedded Language Tags, e.g. <?php ?> */ .hljs-meta, /* prevent top level .keyword and .string scopes from leaking into meta by accident */ .hljs-meta .hljs-keyword, .hljs-meta .hljs-string { color: #444444; } .hljs-meta .hljs-keyword, /* for v10 compatible themes */ .hljs-meta-keyword { font-weight: bold; }
Qeole/Enlight
hljs/styles/base16/black-metal-bathory.css
CSS
mpl-2.0
3,998
package vct.col.util; public class FieldDefinition extends AnyDefinition{ private ClassDefinition parent; public final boolean is_static; public FieldDefinition(String name,boolean is_static,ClassDefinition parent){ super(name); this.parent=parent; this.is_static=is_static; } public ClassDefinition getParent() { return parent; } }
sccblom/vercors
vercors/src/main/java/vct/col/util/FieldDefinition.java
Java
mpl-2.0
370
package reaperlog import ( log "github.com/Sirupsen/logrus" "github.com/rifflock/lfshook" "go.mozilla.org/mozlogrus" ) var config LogConfig type LogConfig struct { Extras bool } func EnableExtras() { config.Extras = true } func EnableMozlog() { mozlogrus.Enable("Reaper") } func Extras() bool { return config.Extras } func SetConfig(c *LogConfig) { config = *c } func AddLogFile(filename string) { log.AddHook(lfshook.NewHook(lfshook.PathMap{ log.DebugLevel: filename, log.InfoLevel: filename, log.WarnLevel: filename, log.ErrorLevel: filename, log.FatalLevel: filename, log.PanicLevel: filename, })) } func Debug(format string, args ...interface{}) { log.Debugf(format, args...) } func Info(format string, args ...interface{}) { log.Infof(format, args...) } func Warning(format string, args ...interface{}) { log.Warningf(format, args...) } func Fatal(format string, args ...interface{}) { log.Fatalf(format, args...) } func Panic(format string, args ...interface{}) { log.Panicf(format, args...) } func Error(format string, args ...interface{}) { log.Errorf(format, args...) }
milescrabill/reaper
reaperlog/reaperlog.go
GO
mpl-2.0
1,123
# -*- coding: utf-8 -*- ############################################################################### # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. ############################################################################### import ws import unittest class TestCollapse(unittest.TestCase): def test_collapse(self): result = ws.collapse(" ") self.assertEqual(result, "") result = ws.collapse(" foo") self.assertEqual(result, "foo") result = ws.collapse("foo ") self.assertEqual(result, "foo") result = ws.collapse(" foo bar ") self.assertEqual(result, "foo bar") result = ws.collapse("foo\t\nbar\r") self.assertEqual(result, "foo bar") if __name__ == '__main__': unittest.main()
gerv/slic
test/data/identification/test_ws.py
Python
mpl-2.0
941
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* ===== scrollbars.css ================================================= == Styles used by XUL scrollbar-related elements. ======================================================================= */ @namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"); @namespace html url("http://www.w3.org/1999/xhtml"); /* namespace for HTML elements */ /* ::::: scrollbar ::::: */ scrollbar { -moz-binding: url("chrome://global/content/bindings/scrollbar.xml#scrollbar"); cursor: default; } /* ::::: slider ::::: */ slider { min-width: 15px; min-height: 15px; background: url("chrome://global/skin/scrollbar/slider-hrz.gif") repeat-x; } slider[orient="vertical"] { background: url("chrome://global/skin/scrollbar/slider-vrt.gif") repeat-y; } /* ::::: borders for thumb and buttons ::::: */ thumb, scrollbarbutton { border: 3px solid; -moz-border-top-colors: #000000 #E4EBF2 #C3CAD2; -moz-border-right-colors: #000000 #8F9DAD #A4AFBB; -moz-border-bottom-colors: #000000 #8F9DAD #A4AFBB; -moz-border-left-colors: #000000 #E4EBF2 #C3CAD2; background: #B1BBC5 50% 50% no-repeat; } thumb:active { background-color: #C2CCD6; -moz-border-top-colors: #111111 #F5FCF3 #D4DBE3; -moz-border-right-colors: #111111 #9FAEBE #B5BFCC; -moz-border-bottom-colors: #111111 #9FAEBE #B5BFCC; -moz-border-left-colors: #111111 #D5FCF3 #D4DBE3; } /* ::::: thumb (horizontal) ::::: */ thumb { min-height: 18px; background-image: url("chrome://global/skin/scrollbar/thumb-vrt-grip.gif"); } thumb[orient="horizontal"] { min-width: 18px; background-image: url("chrome://global/skin/scrollbar/thumb-hrz-grip.gif"); } /* ::::: scrollbar button ::::: */ scrollbarbutton { width: 15px; height: 15px; max-width: 15px; max-height: 15px; -moz-box-flex: 1; } scrollbarbutton[disabled="true"], scrollbarbutton[active="true"], scrollbarbutton:hover:active { border-left-width: 2px; border-right-width: 2px; -moz-border-top-colors: #000000 #708092 #939FAD; -moz-border-right-colors: #000000 #718193 #9EA9B5; -moz-border-bottom-colors: #000000 #8795A4 #929EAC; -moz-border-left-colors: #000000 #ADB6C0 #9EA9B5; background-color: #9CA8B4; } /* ::::: square at the corner of two scrollbars ::::: */ scrollcorner { -moz-binding: url("chrome://global/content/bindings/scrollbar.xml#scrollbar-base"); width: 15px; cursor: default; background-color: #B1BBC5; } /* ..... increment .... */ scrollbarbutton[type="increment"] { background-image: url("chrome://global/skin/scrollbar/btn-rit.gif") } scrollbar[orient="vertical"] > scrollbarbutton[type="increment"] { background-image: url("chrome://global/skin/scrollbar/btn-dn.gif") } /* ..... decrement .... */ scrollbarbutton[type="decrement"] { background-image: url("chrome://global/skin/scrollbar/btn-lft.gif") } scrollbar[orient="vertical"] > scrollbarbutton[type="decrement"] { background-image: url("chrome://global/skin/scrollbar/btn-up.gif") } /* :::::::::::::::::::::::::::::::::::::::::::::::::::::::: */ /* ::::::::::::::::::::: MEDIA PRINT :::::::::::::::::::::: */ /* :::::::::::::::::::::::::::::::::::::::::::::::::::::::: */ @media print { /* ::::: slider ::::: */ html|div slider { height: 15px; background: url("chrome://global/skin/scrollbar/slider-hrz.gif") repeat-x; } html|div slider[orient="vertical"] { width: 15px; background: url("chrome://global/skin/scrollbar/slider-vrt.gif") repeat-y; } /* ::::: borders for thumb and buttons ::::: */ html|div thumb, html|div scrollbarbutton { border: 3px solid; -moz-border-top-colors: #000000 #E4EBF2 #C3CAD2; -moz-border-right-colors: #000000 #8F9DAD #A4AFBB; -moz-border-bottom-colors: #000000 #8F9DAD #A4AFBB; -moz-border-left-colors: #000000 #E4EBF2 #C3CAD2; background: #B1BBC5 50% 50% no-repeat; } html|div thumb:active { background-color: #C2CCD6; -moz-border-top-colors: #111111 #F5FCF3 #D4DBE3; -moz-border-right-colors: #111111 #9FAEBE #B5BFCC; -moz-border-bottom-colors: #111111 #9FAEBE #B5BFCC; -moz-border-left-colors: #111111 #D5FCF3 #D4DBE3; } /* ::::: thumb (horizontal) ::::: */ html|div thumb { min-height: 18px; background-image: url("chrome://global/skin/scrollbar/thumb-vrt-grip.gif"); } html|div thumb[orient="horizontal"] { min-width: 18px; background-image: url("chrome://global/skin/scrollbar/thumb-hrz-grip.gif"); } /* ::::: scrollbar button ::::: */ html|div scrollbarbutton { width: 15px; height: 15px; } html|div scrollbarbutton[disabled="true"], html|div scrollbarbutton[active="true"], html|div scrollbarbutton:hover:active { border-left-width: 2px; border-right-width: 2px; -moz-border-top-colors: #000000 #708092 #939FAD; -moz-border-right-colors: #000000 #718193 #9EA9B5; -moz-border-bottom-colors: #000000 #8795A4 #929EAC; -moz-border-left-colors: #000000 #ADB6C0 #9EA9B5; background-color: #9CA8B4; } /* ..... increment .... */ html|div scrollbarbutton[type="increment"] { background-image: url("chrome://global/skin/scrollbar/btn-rit.gif") } html|div scrollbar[orient="vertical"] > scrollbarbutton[type="increment"] { background-image: url("chrome://global/skin/scrollbar/btn-dn.gif") } /* ..... decrement .... */ html|div scrollbarbutton[type="decrement"] { background-image: url("chrome://global/skin/scrollbar/btn-lft.gif") } html|div scrollbar[orient="vertical"] > scrollbarbutton[type="decrement"] { background-image: url("chrome://global/skin/scrollbar/btn-up.gif") } }
Lootyhoof/pastmodern-revisited
src/chrome/global/scrollbars.css
CSS
mpl-2.0
5,831
// weather_base_url comes in via django and must be set before including this file $(document).ready(function() { // Save the representative id data_to_save['scenario_id'] = $('#scenario_id').val(); // Initializes description $('#weather-select').change(); }); $('#weather-select').change(function() { var option_id = $('#weather-select').val(); var weather_data_url = weather_base_url + option_id + "/"; data_to_save['weather_id'] = option_id; updateWeatherCharts(weather_data_url); }); function change_climate(type) { // IDs of each climate type var tropical_rainforest = 1; var tropical_monsoonal = 2; var wet_savannah = 3; var dry_savannah = 9; var arid = 8; switch (type) { case 'Humid': $('#weather-select').val(tropical_rainforest).change(); break; case 'Moist Subhumid': $('#weather-select').val(tropical_monsoonal).change(); break; case 'Dry Subhumid': $('#weather-select').val(wet_savannah).change(); break; case 'Semi Arid': $('#weather-select').val(dry_savannah).change(); break; case 'Arid': $('#weather-select').val(arid).change(); break; default: alert('Zone ' + type + ' is not valid.'); } }
vecnet/vnetsource
ts_repr/static/ts_repr/js/creation/weather.js
JavaScript
mpl-2.0
1,362
import logging from django.conf import settings from kombu import (Exchange, Queue) from kombu.mixins import ConsumerMixin from treeherder.etl.common import fetch_json from treeherder.etl.tasks.pulse_tasks import (store_pulse_jobs, store_pulse_resultsets) logger = logging.getLogger(__name__) class PulseConsumer(ConsumerMixin): """ Consume jobs from Pulse exchanges """ def __init__(self, connection, queue_suffix): self.connection = connection self.consumers = [] self.queue = None config = settings.PULSE_DATA_INGESTION_CONFIG if not config: raise ValueError("PULSE_DATA_INGESTION_CONFIG is required for the " "JobConsumer class.") self.queue_name = "queue/{}/{}".format(config.username, queue_suffix) def get_consumers(self, Consumer, channel): return [ Consumer(**c) for c in self.consumers ] def bind_to(self, exchange, routing_key): if not self.queue: self.queue = Queue( name=self.queue_name, channel=self.connection.channel(), exchange=exchange, routing_key=routing_key, durable=settings.PULSE_DATA_INGESTION_QUEUES_DURABLE, auto_delete=settings.PULSE_DATA_INGESTION_QUEUES_AUTO_DELETE ) self.consumers.append(dict(queues=self.queue, callbacks=[self.on_message])) # just in case the queue does not already exist on Pulse self.queue.declare() else: self.queue.bind_to(exchange=exchange, routing_key=routing_key) def unbind_from(self, exchange, routing_key): self.queue.unbind_from(exchange, routing_key) def close(self): self.connection.release() def prune_bindings(self, new_bindings): # get the existing bindings for the queue bindings = [] try: bindings = self.get_bindings(self.queue_name)["bindings"] except Exception: logger.error("Unable to fetch existing bindings for {}".format( self.queue_name)) logger.error("Data ingestion may proceed, " "but no bindings will be pruned") # Now prune any bindings from the queue that were not # established above. # This indicates that they are no longer in the config, and should # therefore be removed from the durable queue bindings list. for binding in bindings: if binding["source"]: binding_str = self.get_binding_str(binding["source"], binding["routing_key"]) if binding_str not in new_bindings: self.unbind_from(Exchange(binding["source"]), binding["routing_key"]) logger.info("Unbound from: {}".format(binding_str)) def get_binding_str(self, exchange, routing_key): """Use consistent string format for binding comparisons""" return "{} {}".format(exchange, routing_key) def get_bindings(self, queue_name): """Get list of bindings from the pulse API""" return fetch_json("{}queue/{}/bindings".format( settings.PULSE_GUARDIAN_URL, queue_name)) class JobConsumer(PulseConsumer): def on_message(self, body, message): store_pulse_jobs.apply_async( args=[body, message.delivery_info["exchange"], message.delivery_info["routing_key"]], routing_key='store_pulse_jobs' ) message.ack() class ResultsetConsumer(PulseConsumer): def on_message(self, body, message): store_pulse_resultsets.apply_async( args=[body, message.delivery_info["exchange"], message.delivery_info["routing_key"]], routing_key='store_pulse_resultsets' ) message.ack()
akhileshpillai/treeherder
treeherder/etl/pulse_consumer.py
Python
mpl-2.0
4,116
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.ECS.DeregisterTaskDefinition -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | NOT YET IMPLEMENTED. -- -- Deregisters the specified task definition. You will no longer be able to run -- tasks from this definition after deregistration. -- -- <http://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DeregisterTaskDefinition.html> module Network.AWS.ECS.DeregisterTaskDefinition ( -- * Request DeregisterTaskDefinition -- ** Request constructor , deregisterTaskDefinition -- ** Request lenses , dtd1TaskDefinition -- * Response , DeregisterTaskDefinitionResponse -- ** Response constructor , deregisterTaskDefinitionResponse -- ** Response lenses , dtdrTaskDefinition ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.ECS.Types import qualified GHC.Exts newtype DeregisterTaskDefinition = DeregisterTaskDefinition { _dtd1TaskDefinition :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'DeregisterTaskDefinition' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dtd1TaskDefinition' @::@ 'Text' -- deregisterTaskDefinition :: Text -- ^ 'dtd1TaskDefinition' -> DeregisterTaskDefinition deregisterTaskDefinition p1 = DeregisterTaskDefinition { _dtd1TaskDefinition = p1 } -- | The 'family' and 'revision' ('family:revision') or full Amazon Resource Name (ARN) -- of the task definition that you want to deregister. dtd1TaskDefinition :: Lens' DeregisterTaskDefinition Text dtd1TaskDefinition = lens _dtd1TaskDefinition (\s a -> s { _dtd1TaskDefinition = a }) newtype DeregisterTaskDefinitionResponse = DeregisterTaskDefinitionResponse { _dtdrTaskDefinition :: Maybe TaskDefinition } deriving (Eq, Read, Show) -- | 'DeregisterTaskDefinitionResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dtdrTaskDefinition' @::@ 'Maybe' 'TaskDefinition' -- deregisterTaskDefinitionResponse :: DeregisterTaskDefinitionResponse deregisterTaskDefinitionResponse = DeregisterTaskDefinitionResponse { _dtdrTaskDefinition = Nothing } -- | The full description of the deregistered task. dtdrTaskDefinition :: Lens' DeregisterTaskDefinitionResponse (Maybe TaskDefinition) dtdrTaskDefinition = lens _dtdrTaskDefinition (\s a -> s { _dtdrTaskDefinition = a }) instance ToPath DeregisterTaskDefinition where toPath = const "/" instance ToQuery DeregisterTaskDefinition where toQuery = const mempty instance ToHeaders DeregisterTaskDefinition instance ToJSON DeregisterTaskDefinition where toJSON DeregisterTaskDefinition{..} = object [ "taskDefinition" .= _dtd1TaskDefinition ] instance AWSRequest DeregisterTaskDefinition where type Sv DeregisterTaskDefinition = ECS type Rs DeregisterTaskDefinition = DeregisterTaskDefinitionResponse request = post "DeregisterTaskDefinition" response = jsonResponse instance FromJSON DeregisterTaskDefinitionResponse where parseJSON = withObject "DeregisterTaskDefinitionResponse" $ \o -> DeregisterTaskDefinitionResponse <$> o .:? "taskDefinition"
romanb/amazonka
amazonka-ecs/gen/Network/AWS/ECS/DeregisterTaskDefinition.hs
Haskell
mpl-2.0
4,182
#include "zlib.h" #include <util/memory/addstorage.h> #include <util/generic/utility.h> #include <contrib/libs/zlib/zlib.h> #include <cstdio> #include <cstring> namespace { static const int opts[] = { //Auto 15 + 32, //ZLib 15 + 0, //GZip 15 + 16, //Raw -15 }; class TZLibCommon { public: inline TZLibCommon() throw () { memset(Z(), 0, sizeof(*Z())); } inline ~TZLibCommon() throw () { } inline const char* GetErrMsg() const throw () { return Z()->msg != 0 ? Z()->msg : "unknown error"; } inline z_stream* Z() const throw () { return (z_stream*)(&Z_); } private: z_stream Z_; }; static inline ui32 MaxPortion(size_t s) throw () { return (ui32)Min<size_t>(Max<ui32>(), s); } struct TChunkedZeroCopyInput { inline TChunkedZeroCopyInput(IZeroCopyInput* in) : In(in) , Buf(0) , Len(0) { } template <class P, class T> inline bool Next(P** buf, T* len) { if (!Len) { if (!In->Next(&Buf, &Len)) { return false; } } const T toread = (T)Min((size_t)Max<T>(), Len); *len = toread; *buf = (P*)Buf; Buf += toread; Len -= toread; return true; } IZeroCopyInput* In; const char* Buf; size_t Len; }; } class TZLibDecompress::TImpl: private TZLibCommon, public TChunkedZeroCopyInput { public: inline TImpl(IZeroCopyInput* in, ZLib::StreamType type) : TChunkedZeroCopyInput(in) { if (inflateInit2(Z(), opts[type]) != Z_OK) { ythrow TZLibDecompressorError() << "can not init inflate engine"; } } virtual ~TImpl() { inflateEnd(Z()); } inline size_t Read(void* buf, size_t size) { Z()->next_out = (unsigned char*)buf; Z()->avail_out = size; while (true) { if (Z()->avail_in == 0) { if (!FillInputBuffer()) { return 0; } } switch (inflate(Z(), Z_SYNC_FLUSH)) { case Z_STREAM_END: { if (inflateReset(Z()) != Z_OK) { ythrow TZLibDecompressorError() << "inflate reset error(" << GetErrMsg() << ")"; } } case Z_OK: { const size_t processed = size - Z()->avail_out; if (processed) { return processed; } break; } default: ythrow TZLibDecompressorError() << "inflate error(" << GetErrMsg() << ")"; } } } private: inline bool FillInputBuffer() { return Next(&Z()->next_in, &Z()->avail_in); } }; namespace { class TDecompressStream: public IZeroCopyInput, public TZLibDecompress::TImpl, public TAdditionalStorage<TDecompressStream> { public: inline TDecompressStream(TInputStream* input, ZLib::StreamType type) : TZLibDecompress::TImpl(this, type) , Stream_(input) { } private: virtual bool DoNext(const void** ptr, size_t* len) { void* buf = AdditionalData(); *ptr = buf; *len = Stream_->Read(buf, AdditionalDataLength()); return *len; } private: TInputStream* Stream_; }; typedef TZLibDecompress::TImpl TZeroCopyDecompress; } class TZLibCompress::TImpl: public TAdditionalStorage<TImpl>, private TZLibCommon { template <class T> static inline T Type(T type) { if (type == ZLib::Auto) { return ZLib::ZLib; } return type; } public: inline TImpl(const TParams& p) : Stream_(p.Out) { if (deflateInit2(Z(), Min<size_t>(9, p.CompressionLevel), Z_DEFLATED, opts[Type(p.Type)], 8, Z_DEFAULT_STRATEGY)) { ythrow TZLibCompressorError() << "can not init inflate engine"; } if (+p.Dict) { if (deflateSetDictionary(Z(), (const Bytef*)~p.Dict, +p.Dict)) { ythrow TZLibCompressorError() << "can not set deflate dictionary"; } } Z()->next_out = TmpBuf(); Z()->avail_out = TmpBufLen(); } inline ~TImpl() throw () { deflateEnd(Z()); } inline void Write(const void* buf, size_t size) { const Bytef* b = (const Bytef*)buf; const Bytef* e = b + size; do { b = WritePart(b, e); } while (b < e); } inline const Bytef* WritePart(const Bytef* b, const Bytef* e) { Z()->next_in = const_cast<Bytef*>(b); Z()->avail_in = MaxPortion(e - b); while (Z()->avail_in) { const int ret = deflate(Z(), Z_NO_FLUSH); switch (ret) { case Z_OK: continue; case Z_BUF_ERROR: FlushBuffer(); break; default: ythrow TZLibCompressorError() << "deflate error(" << GetErrMsg() << ")"; } } return Z()->next_in; } inline void Flush() { } inline void FlushBuffer() { Stream_->Write(TmpBuf(), TmpBufLen() - Z()->avail_out); Z()->next_out = TmpBuf(); Z()->avail_out = TmpBufLen(); } inline void Finish() { int ret = deflate(Z(), Z_FINISH); while (ret == Z_OK || ret == Z_BUF_ERROR) { FlushBuffer(); ret = deflate(Z(), Z_FINISH); } if (ret == Z_STREAM_END) { Stream_->Write(TmpBuf(), TmpBufLen() - Z()->avail_out); } else { ythrow TZLibCompressorError() << "deflate error(" << GetErrMsg() << ")"; } } private: inline unsigned char* TmpBuf() throw () { return (unsigned char*)AdditionalData(); } inline size_t TmpBufLen() const throw () { return AdditionalDataLength(); } private: TOutputStream* Stream_; }; TZLibDecompress::TZLibDecompress(TInputStream* input, ZLib::StreamType type, size_t buflen) : Impl_(new (buflen) TDecompressStream(input, type)) { } TZLibDecompress::TZLibDecompress(IZeroCopyInput* input, ZLib::StreamType type) : Impl_(new TZeroCopyDecompress(input, type)) { } TZLibDecompress::~TZLibDecompress() throw () { } size_t TZLibDecompress::DoRead(void* buf, size_t size) { return Impl_->Read(buf, MaxPortion(size)); } void TZLibCompress::Init(const TParams& opts) { Impl_.Reset(new (opts.BufLen) TImpl(opts)); } void TZLibCompress::TDestruct::Destroy(TImpl* impl) { delete impl; } TZLibCompress::~TZLibCompress() throw () { try { Finish(); } catch (...) { } } void TZLibCompress::DoWrite(const void* buf, size_t size) { if (!Impl_) { ythrow TZLibCompressorError() << "can not write to finished zlib stream"; } Impl_->Write(buf, size); } void TZLibCompress::DoFlush() { if (Impl_) { Impl_->Flush(); } } void TZLibCompress::DoFinish() { THolder<TImpl> impl(Impl_.Release()); if (impl) { impl->Finish(); } }
evilmucedin/tomita-parser
src/util/stream/zlib.cpp
C++
mpl-2.0
7,440
# Neutrino Environment Middleware `@neutrinojs/env` is Neutrino middleware for injecting environment variable definitions into source code at `process.env`. You can use this to make a custom environment variable (e.g. an API server backend to use) available inside your project. Always injects `process.env.NODE_ENV`, unless overridden. [![NPM version][npm-image]][npm-url] [![NPM downloads][npm-downloads]][npm-url] [![Join the Neutrino community on Spectrum][spectrum-image]][spectrum-url] ## Requirements - Node.js v6 LTS, v8, v9 - Yarn v1.2.1+, or npm v5.4+ - Neutrino v8 ## Installation `@neutrinojs/env` can be installed via the Yarn or npm clients. #### Yarn ```bash ❯ yarn add @neutrinojs/env ``` #### npm ```bash ❯ npm install --save @neutrinojs/env ``` ## Usage `@neutrinojs/env` can be consumed from the Neutrino API, middleware, or presets. Require this package and plug it into Neutrino: ```js // Using function middleware format const env = require('@neutrinojs/env'); // Use with default options neutrino.use(env); // Usage with additional environment variables neutrino.use(env, ['SECRET_KEY']); ``` ```js // Using object or array middleware format // Use with default options module.exports = { use: ['@neutrinojs/env'] }; // Usage with additional environment variables module.exports = { use: [ ['@neutrinojs/env', ['SECRET_KEY']] ] }; ``` This middleware optionally accepts an array of environment variables to additionally inject into source code. ## Customization `@neutrinojs/env` creates some conventions to make overriding the configuration easier once you are ready to make changes. ### Plugins The following is a list of plugins and their identifiers which can be overridden: | Name | Description | Environments and Commands | | --- | --- | --- | | `env` | Inject environment variables into source code at `process.env`. | all | ## Contributing This middleware is part of the [neutrino-dev](https://github.com/mozilla-neutrino/neutrino-dev) repository, a monorepo containing all resources for developing Neutrino and its core presets and middleware. Follow the [contributing guide](https://neutrino.js.org/contributing) for details. [npm-image]: https://img.shields.io/npm/v/@neutrinojs/env.svg [npm-downloads]: https://img.shields.io/npm/dt/@neutrinojs/env.svg [npm-url]: https://npmjs.org/package/@neutrinojs/env [spectrum-image]: https://withspectrum.github.io/badge/badge.svg [spectrum-url]: https://spectrum.chat/neutrino
eliperelman/neutrino-dev
packages/env/README.md
Markdown
mpl-2.0
2,494
# encoding: utf-8 # # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http:# mozilla.org/MPL/2.0/. # # Contact: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import absolute_import, division, unicode_literals from jx_base.expressions import NumberOp as NumberOp_ from jx_sqlite.expressions import _utils from jx_sqlite.expressions._utils import SQLang, check from mo_dots import wrap from mo_sql import sql_coalesce class NumberOp(NumberOp_): @check def to_sql(self, schema, not_null=False, boolean=False): value = SQLang[self.term].to_sql(schema, not_null=True) acc = [] for c in value: for t, v in c.sql.items(): if t == "s": acc.append("CAST(" + v + " as FLOAT)") else: acc.append(v) if not acc: return wrap([]) elif len(acc) == 1: return wrap([{"name": ".", "sql": {"n": acc[0]}}]) else: return wrap([{"name": ".", "sql": {"n": sql_coalesce(acc)}}]) _utils.NumberOp = NumberOp
klahnakoski/TestLog-ETL
vendor/jx_sqlite/expressions/number_op.py
Python
mpl-2.0
1,194
package validdata.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import validdata.dao.StudentDao; import validdata.entity.Student; import validdata.service.StudentService; /** * 学生信息Service实现类 * @author Administrator * */ @Service("studentService") public class StudentServiceImpl implements StudentService{ @Resource private StudentDao studentDao; @Override public void add(Student student) { studentDao.save(student); } }
luguanxing/Web-Projects
SpringBoot/08-springboot表单验证/src/main/java/validdata/service/impl/StudentServiceImpl.java
Java
mpl-2.0
507
package openid import ( "fmt" "net/http" "github.com/dgrijalva/jwt-go" ) // SetupErrorCode is the type of error code that can // be returned by the operations done during middleware setup. type SetupErrorCode uint32 // Setup error constants. const ( SetupErrorInvalidIssuer SetupErrorCode = iota // Invalid issuer provided during setup. SetupErrorInvalidClientIDs // Invalid client id collection provided during setup. SetupErrorEmptyProviderCollection // Empty collection of providers provided during setup. ) // ValidationErrorCode is the type of error code that can // be returned by the operations done during token validation. type ValidationErrorCode uint32 // Validation error constants. const ( ValidationErrorAuthorizationHeaderNotFound ValidationErrorCode = iota // Authorization header not found on request. ValidationErrorAuthorizationHeaderWrongFormat // Authorization header unexpected format. ValidationErrorAuthorizationHeaderWrongSchemeName // Authorization header unexpected scheme. ValidationErrorJwtValidationFailure // Jwt token validation failed with a known error. ValidationErrorJwtValidationUnknownFailure // Jwt token validation failed with an unknown error. ValidationErrorInvalidAudienceType // Unexpected token audience type. ValidationErrorInvalidAudience // Unexpected token audience content. ValidationErrorAudienceNotFound // Unexpected token audience value. Audience not registered. ValidationErrorInvalidIssuerType // Unexpected token issuer type. ValidationErrorInvalidIssuer // Unexpected token issuer content. ValidationErrorIssuerNotFound // Unexpected token value. Issuer not registered. ValidationErrorGetOpenIdConfigurationFailure // Failure while retrieving the OIDC configuration. ValidationErrorDecodeOpenIdConfigurationFailure // Failure while decoding the OIDC configuration. ValidationErrorGetJwksFailure // Failure while retrieving jwk set. ValidationErrorDecodeJwksFailure // Failure while decoding the jwk set. ValidationErrorEmptyJwk // Empty jwk returned. ValidationErrorEmptyJwkKey // Empty jwk key set returned. ValidationErrorMarshallingKey // Error while marshalling the signing key. ValidationErrorKidNotFound // Key identifier not found. ValidationErrorInvalidSubjectType // Unexpected token subject type. ValidationErrorInvalidSubject // Unexpected token subject content. ValidationErrorSubjectNotFound // Token missing the 'sub' claim. ValidationErrorIdTokenEmpty // Empty ID token. ValidationErrorEmptyProviders // Empty collection of providers. ) const setupErrorMessagePrefix string = "Setup Error." const validationErrorMessagePrefix string = "Validation Error." // SetupError represents the error returned by operations called during // middleware setup. type SetupError struct { Err error Code SetupErrorCode Message string } // Error returns a formatted string containing the error Message. func (se SetupError) Error() string { return fmt.Sprintf("Setup error. %v", se.Message) } // ValidationError represents the error returned by operations called during // token validation. type ValidationError struct { Err error Code ValidationErrorCode Message string HTTPStatus int } // The ErrorHandlerFunc represents the function used to handle errors during token // validation. Applications can have their own implementation of this function and // register it using the ErrorHandler option. Through this extension point applications // can choose what to do upon different error types, for instance return an certain HTTP Status code // and/or include some detailed message in the response. // This function returns false if the next handler registered after the ID Token validation // should be executed when an error is found or true if the execution should be stopped. type ErrorHandlerFunc func(error, http.ResponseWriter, *http.Request) bool // Error returns a formatted string containing the error Message. func (ve ValidationError) Error() string { return fmt.Sprintf("Validation error. %v", ve.Message) } // jwtErrorToOpenIdError converts errors of the type *jwt.ValidationError returned during token validation into errors of type *ValidationError func jwtErrorToOpenIdError(e error) *ValidationError { if jwtError, ok := e.(*jwt.ValidationError); ok { if (jwtError.Errors & (jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired | jwt.ValidationErrorSignatureInvalid)) != 0 { return &ValidationError{Code: ValidationErrorJwtValidationFailure, Message: "Jwt token validation failed.", HTTPStatus: http.StatusUnauthorized} } if (jwtError.Errors & jwt.ValidationErrorMalformed) != 0 { return &ValidationError{Code: ValidationErrorJwtValidationFailure, Message: "Jwt token validation failed.", HTTPStatus: http.StatusBadRequest} } if (jwtError.Errors & jwt.ValidationErrorUnverifiable) != 0 { // TODO: improve this once https://github.com/dgrijalva/jwt-go/issues/108 is resolved. // Currently jwt.Parse does not surface errors returned by the KeyFunc. return &ValidationError{Code: ValidationErrorJwtValidationFailure, Message: jwtError.Error(), HTTPStatus: http.StatusUnauthorized} } } return &ValidationError{Code: ValidationErrorJwtValidationUnknownFailure, Message: "Jwt token validation failed with unknown error.", HTTPStatus: http.StatusInternalServerError} } func validationErrorToHTTPStatus(e error, rw http.ResponseWriter, req *http.Request) (halt bool) { if verr, ok := e.(*ValidationError); ok { http.Error(rw, verr.Message, verr.HTTPStatus) } else { rw.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(rw, e.Error()) } return true }
mvdan/tyk
vendor/github.com/TykTechnologies/openid2go/openid/errors.go
GO
mpl-2.0
6,707
#include "attach.h" #include "details/atom/classdef-table.h" #include "details/reporting/report.h" #include <unordered_map> #include "mapping.h" using namespace Yuni; namespace ny::compiler { bool attach(ny::compiler::Compdb& compdb, ny::compiler::Source& source) { auto& sequence = source.sequence(); auto& cdeftable = compdb.cdeftable; auto& mutex = compdb.mutex; Pass::MappingOptions options; return Pass::map(cdeftable.atoms.root, cdeftable, mutex, sequence, options); } } // ny::compiler
nany-lang/nanyc
bootstrap/libnanyc/details/pass/d-object-map/attach.cpp
C++
mpl-2.0
502
package websheets; // a bunch of public static methods without side-effects import java.util.ArrayList; import java.util.Arrays; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.lang.reflect.Array; public class Utils { // string representation of class public static String classToString(Class<?> clazz) { if (clazz.isArray()) return classToString(clazz.getComponentType())+"[]"; if (clazz.isPrimitive()) return clazz.toString(); return clazz.getSimpleName(); } // string representation of list of classes, like arg list public static String classListToString(Class<?>[] classes) { String result = "("; for (int i=0; i<classes.length; i++) { if (i > 0) result += ","; result += classToString(classes[i]); } return result+")"; } // escape necessary html entities public static String esc(String S) { return S.replaceAll("&", "&amp;").replaceAll(">", "&gt;") .replaceAll("<", "&lt;").replaceAll(" ", " &nbsp;"); } // print <pre> element containing this text with these attributes public static String pre(String S, String attr) { String adjust = S.equals("") ? "<br>" : ""; return "<pre "+attr+">" + adjust + esc(S) + "</pre>"; } // or no attributes public static String pre(String S) {return pre(S, "");} // print <code> element containing this text with these attributes public static String code(String S, String attr) { if (S==null) return "[NULL]"; return "<code "+attr+">" + esc(S) + "</code>"; } // or no attributes public static String code(String S) {return code(S, "");} // accept object public static String code(Object O) {return code(O.toString(), "");} // convert object to human-readable form public static String repr(Object O) { if (O instanceof String) { return '"' + (String)O + '"'; } else if (O == null) { return "null"; } else if (O.getClass().isArray()) { String tmp = "{"; for (int i=0; i<Array.getLength(O); i++) { if (i != 0) tmp += ", "; tmp += repr(Array.get(O, i)); } return tmp + "}"; } else return O.toString(); // including NamedObjects } // remove spaces from end of string private static final Pattern RTRIMEND = Pattern.compile(" +$"); public static String rtrim(String S) { return RTRIMEND.matcher(S).replaceAll(""); } // trim if options dictate it public static String rtrimConditional(String S, Options o) { return o.ignoreTrailingSpaces ? rtrim(S) : S; } // pattern from regular expression for real number literals // note that this requires a period inside the number! // so it is not "all double literals" but rather // "things a sane problem could print for a double" // except, it doesn't catch NaN, infinity, octal, etc private static final Pattern REAL_NUMBER = Pattern.compile("[+-]?(\\d+\\.\\d*|\\.\\d+)"+ "([eE][+-]?\\d+)?"); // split string at "real number" literals // return alternating array of non-number text and number tokens // note that some strings like "2.2.2" are sort of ambiguous public static String[] splitAtReals(String a) { ArrayList<String> result = new ArrayList<String>(); int lastend = 0; Matcher m = REAL_NUMBER.matcher(a); while (m.find()) { result.add(a.substring(lastend, m.start())); result.add(m.group()); lastend = m.end(); } result.add(a.substring(lastend)); return result.toArray(new String[result.size()]); } // same within relative error 1E-4? // Except: if reference is 0, allow absolute error 1E-4 // student first, reference second public static boolean equalsApprox(double s, double r, Options o) { if (r == 0) return Math.abs(s) <= o.realTolerance; return Math.abs(s-r) <= o.realTolerance * Math.max(Math.abs(s), Math.abs(r)); } // are these equal, discounting errors and formatting of doubles? // student first, reference second (real comparison is asymmetric) // does not normalize for trailing whitespace. // accepts multi-line strings (\n treated like any other character) public static boolean equalsApprox(String sline, String rline, Options o) { if (!o.ignoreRealFormatting) return sline.equals(rline); String[] ssegments = splitAtReals(sline); String[] rsegments = splitAtReals(rline); if (rsegments.length != ssegments.length) return false; for (int i=0; i<rsegments.length; i++) if (i%2 == 0 && !rsegments[i].equals(ssegments[i]) || i%2 != 0 && !equalsApprox(Double.parseDouble(rsegments[i]), Double.parseDouble(ssegments[i]), o)) return false; return true; } // similar to clone public static Object semicopy(Object O) { // basic immutable types if (O == null || O instanceof String || O instanceof Integer || O instanceof Long || O instanceof Character || O instanceof Boolean || O instanceof Short || O instanceof Float || O instanceof Double || O instanceof Byte) return O; if (O instanceof int[]) return Arrays.copyOf((int[])O, ((int[])O).length); if (O instanceof short[]) return Arrays.copyOf((short[])O, ((short[])O).length); if (O instanceof long[]) return Arrays.copyOf((long[])O, ((long[])O).length); if (O instanceof byte[]) return Arrays.copyOf((byte[])O, ((byte[])O).length); if (O instanceof boolean[]) return Arrays.copyOf((boolean[])O, ((boolean[])O).length); if (O instanceof float[]) return Arrays.copyOf((float[])O, ((float[])O).length); if (O instanceof double[]) return Arrays.copyOf((double[])O, ((double[])O).length); if (O instanceof char[]) return Arrays.copyOf((char[])O, ((char[])O).length); if (O instanceof Object[]) { Class cType = O.getClass().getComponentType(); Object[] OA = (Object[])O; Object[] r = (Object[]) Array.newInstance(cType, OA.length); for (int i=0; i<OA.length; i++) r[i] = semicopy(OA[i]); return r; } if (opaque(O)) return O; throw new RuntimeException("Don't know how to semicopy "+O.toString()+O.getClass()); } // is this a complex object? public static boolean opaque(Object o) { if (o==null) return false; String qualname = o.getClass().toString().substring(6); // trim "class " return qualname.startsWith("student.") || qualname.startsWith("reference.") || qualname.startsWith("stdlibpack."); } // is this a stdlib object? public static boolean inStdlib(Object o) { String qualname = o.getClass().toString(); return qualname.startsWith("stdlibpack."); } // student first then reference, where possible public static boolean smartEquals(Object a, Object b, Options o) { if (a == null || b == null) return (a == null && b == null); if (inStdlib(a) || inStdlib(b)) return (a.getClass() == b.getClass()); // for stdlibpack.Queue etc if (opaque(a) || opaque(b)) return opaque(a) && opaque(b); if (a.getClass().isArray() != b.getClass().isArray()) return false; if (a.getClass().isArray()) { if (Array.getLength(a) != Array.getLength(b)) return false; for (int i=0; i<Array.getLength(a); i++) if (!smartEquals(Array.get(a, i), Array.get(b, i), o)) return false; return true; } if (a.getClass() == Double.class) return equalsApprox((Double)a, (Double)b, o); if (a.getClass() == Float.class) return equalsApprox((Float)a, (Float)b, o); if (a.getClass() == String.class) return equalsApprox((String)a, (String)b, o); return a.equals(b); } // are they different? return null if not, html description if so public static String describeOutputDifference(String stu, String ref, Options o) { String[] stulines = stu.split("\n", -1); String[] reflines = ref.split("\n", -1); int samelines = 0; while (samelines < Math.min(stulines.length, reflines.length) && equalsApprox(rtrimConditional(stulines[samelines], o), rtrimConditional(reflines[samelines], o), o)) samelines++; // were they the same? if (samelines == stulines.length && samelines == reflines.length) return null; // yup! // two special cases if (samelines == stulines.length - 1 && samelines == reflines.length && rtrimConditional(stulines[stulines.length - 1], o).equals("")) return "Your program printed this output:" + pre(stu) + " which is almost correct but <i>an extra newline character was printed at the end</i>."; if (samelines == reflines.length - 1 && samelines == stulines.length && rtrimConditional(reflines[reflines.length - 1], o).equals("")) return "Your program printed this output:" + pre(stu) + " which is almost correct but <i>a newline character is missing at the end</i>."; // general case final int samelines2 = samelines; // woo java 8! wouldn't have to do this since samelines is effectively final final StringBuilder sb = new StringBuilder(); class DescriptionLoop { void handle(String[] lines) { if (lines.length == 1) { if (lines[0].equals("")) sb.append("<pre><i>(no output)</i></pre>"); else sb.append("<pre>"+esc(lines[0])+"</pre>"); return; } sb.append("<pre><span class='before-diff-line'>"); for (int i=0; i<lines.length; i++) { if (i==samelines2) sb.append("</span><span class='diff-line'>"); sb.append(esc(lines[i])); if (i==samelines2) sb.append("</span><span class='after-diff-line'>"); if (i != lines.length-1 || lines.length == 1) sb.append("<br>"); // wasn't student output for i==length-1, but add it to fix pre appearance } sb.append("</span></pre>"); } }; DescriptionLoop dl = new DescriptionLoop(); boolean stured = samelines < stulines.length - 1 || samelines == stulines.length - 1 && !rtrim(stulines[stulines.length-1]).equals(""); boolean refred = samelines < reflines.length - 1 || samelines == reflines.length - 1 && !rtrim(reflines[reflines.length-1]).equals(""); sb.append("Your program printed this output" + (stured ? " (first difference in red)" : "") + ":"); dl.handle(stulines); sb.append("It was supposed to print this output" + ((samelines < reflines.length) ? " (first difference in red)" : "") + ":"); dl.handle(reflines); return sb.toString(); } public static <T> T failBecauseBlank() { throw new Grader.BlankException(); } }
dz0/websheets
grade_java_files/Utils.java
Java
agpl-3.0
11,738
# Omega Server Command Helpers tests # # Copyright (C) 2013-2014 Mohammed Morsi <mo@morsi.org> # Licensed under the AGPLv3 http://www.gnu.org/licenses/agpl.txt require 'spec_helper' require 'omega/server/command_helpers' module Omega module Server describe CommandHelpers do before(:each) do @ch = OpenStruct.new.extend(CommandHelpers) @ch.registry = double() @ch.node = double() end describe "#update_registry" do it "updates registry entity" do e = Object.new @ch.registry.should_receive(:update). with(e) # TODO test selector @ch.update_registry(e) end end describe "retrieve" do it "retrieves registry entity" do e = Object.new @ch.registry.should_receive(:entity) # TODO test selector @ch.retrieve(e) end end describe "run callbacks" do it "runs callbacks on registry entity" do e1 = double(:id => 42) e2 = double(:id => 43) @ch.registry.should_receive(:safe_exec).and_yield([e1,e2]) e1.should_receive(:run_callbacks).with(:abc) entity = double(:id => 42) @ch.run_callbacks entity, :abc end end describe "#invoke" do it "proxies node.invoke" do @ch.node.should_receive(:invoke).with(42) @ch.invoke 42 end end end # describe CommandHelpers end # module Server end # module Omega
movitto/omega
spec/omega/server/command_helpers_spec.rb
Ruby
agpl-3.0
1,357
# frozen_string_literal: true module SkinnyControllers module Policy class Base attr_accessor :user, :object, :authorized_via_parent # @param [User] user the being to check if they have access to `object` # @param [ActiveRecord::Base] object the object that we are wanting to check # the authorization of `user` for # @param [Boolean] authorized_via_parent if this object is authorized via # a prior authorization from a parent class / association def initialize(user, object, authorized_via_parent: false) self.user = user self.object = object self.authorized_via_parent = authorized_via_parent end # @param [Symbol] method_name # @param [Array] args # @param [Proc] block def method_missing(method_name, *args, &block) # unless the method ends in a question mark, re-route to default method_missing return super unless method_name.to_s =~ /(.+)\?/ action = Regexp.last_match(1) # alias destroy to delete # TODO: this means that a destroy method, if defined, # will never be called.... good or bad? # should there be a difference between delete and destroy? return send('delete?') if action == 'destroy' # we know that these methods don't take any parameters, # so args and block can be ignored SkinnyControllers.logger.warn("method '#{action}' in policy '#{self.class.name}' was not found. Using :default?") send(:default?) end def respond_to_missing?(method_name, include_private = false) method_name.to_s =~ /(.+)\?/ || super end # if a method is not defined for a particular verb or action, # this will be used. # # @example Operation::Object::SendReceipt.run is called, since # `send_receipt` doesn't exist in this class, this `default?` # method will be used. def default? SkinnyControllers.allow_by_default end # this should be used when checking access to a single object def read?(o = object) default? end # this should be used when checking access to multilpe objects # it will call `read?` on each object of the array # # if the operation used a scope to find records from # an association, then `authorized_via_parent` could be true, # in which case, the loop would be skipped. # # TODO: think of a way to override the authorized_via_parent functionality def read_all? return true if authorized_via_parent # Might be deceptive... return true if object.nil? || object.empty? # This is expensive, so try to avoid it # TODO: look in to creating a cache for # these look ups that's invalidated upon # object save accessible = object.map { |ea| read?(ea) } accessible.all? end end end end
NullVoxPopuli/aeonvera
vendor/bundle/ruby/2.4.0/gems/skinny_controllers-0.10.8/lib/skinny_controllers/policy/base.rb
Ruby
agpl-3.0
2,975
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Neil McAnaspie using IMS Development Environment (version 1.51 build 2480.15886) // Copyright (C) 1995-2006 IMS MAXIMS plc. All rights reserved. package ims.core.forms.vitalsignsbloodsugar; import java.io.Serializable; public final class AccessLogic extends BaseAccessLogic implements Serializable { private static final long serialVersionUID = 1L; public boolean isAccessible() { if(!super.isAccessible()) return false; // TODO: Add your conditions here. return true; } }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Core/src/ims/core/forms/vitalsignsbloodsugar/AccessLogic.java
Java
agpl-3.0
2,413
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.RefMan.forms.referraloverviewandkpis; import ims.framework.enumerations.FormMode; public interface IComponent { public void setMode(FormMode mode); public FormMode getMode(); public void initialize(ims.RefMan.vo.CatsReferralRefVo catsReferral); }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/RefMan/src/ims/RefMan/forms/referraloverviewandkpis/IComponent.java
Java
agpl-3.0
2,374
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.ocrr.vo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import ims.framework.enumerations.SortOrder; public class MyOrderComponentQuestionsVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<MyOrderComponentQuestionsVo> { private static final long serialVersionUID = 1L; private ArrayList<MyOrderComponentQuestionsVo> col = new ArrayList<MyOrderComponentQuestionsVo>(); public String getBoClassName() { return null; } public boolean add(MyOrderComponentQuestionsVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { return this.col.add(value); } return false; } public boolean add(int index, MyOrderComponentQuestionsVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { this.col.add(index, value); return true; } return false; } public void clear() { this.col.clear(); } public void remove(int index) { this.col.remove(index); } public int size() { return this.col.size(); } public int indexOf(MyOrderComponentQuestionsVo instance) { return col.indexOf(instance); } public MyOrderComponentQuestionsVo get(int index) { return this.col.get(index); } public boolean set(int index, MyOrderComponentQuestionsVo value) { if(value == null) return false; this.col.set(index, value); return true; } public void remove(MyOrderComponentQuestionsVo instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public boolean contains(MyOrderComponentQuestionsVo instance) { return indexOf(instance) >= 0; } public Object clone() { MyOrderComponentQuestionsVoCollection clone = new MyOrderComponentQuestionsVoCollection(); for(int x = 0; x < this.col.size(); x++) { if(this.col.get(x) != null) clone.col.add((MyOrderComponentQuestionsVo)this.col.get(x).clone()); else clone.col.add(null); } return clone; } public boolean isValidated() { for(int x = 0; x < col.size(); x++) if(!this.col.get(x).isValidated()) return false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(col.size() == 0) return null; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } for(int x = 0; x < col.size(); x++) { String[] listOfOtherErrors = this.col.get(x).validate(); if(listOfOtherErrors != null) { for(int y = 0; y < listOfOtherErrors.length; y++) { listOfErrors.add(listOfOtherErrors[y]); } } } int errorCount = listOfErrors.size(); if(errorCount == 0) return null; String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); return result; } public MyOrderComponentQuestionsVoCollection sort() { return sort(SortOrder.ASCENDING); } public MyOrderComponentQuestionsVoCollection sort(boolean caseInsensitive) { return sort(SortOrder.ASCENDING, caseInsensitive); } public MyOrderComponentQuestionsVoCollection sort(SortOrder order) { return sort(new MyOrderComponentQuestionsVoComparator(order)); } public MyOrderComponentQuestionsVoCollection sort(SortOrder order, boolean caseInsensitive) { return sort(new MyOrderComponentQuestionsVoComparator(order, caseInsensitive)); } @SuppressWarnings("unchecked") public MyOrderComponentQuestionsVoCollection sort(Comparator comparator) { Collections.sort(col, comparator); return this; } public MyOrderComponentQuestionsVo[] toArray() { MyOrderComponentQuestionsVo[] arr = new MyOrderComponentQuestionsVo[col.size()]; col.toArray(arr); return arr; } public Iterator<MyOrderComponentQuestionsVo> iterator() { return col.iterator(); } @Override protected ArrayList getTypedCollection() { return col; } private class MyOrderComponentQuestionsVoComparator implements Comparator { private int direction = 1; private boolean caseInsensitive = true; public MyOrderComponentQuestionsVoComparator() { this(SortOrder.ASCENDING); } public MyOrderComponentQuestionsVoComparator(SortOrder order) { if (order == SortOrder.DESCENDING) { direction = -1; } } public MyOrderComponentQuestionsVoComparator(SortOrder order, boolean caseInsensitive) { if (order == SortOrder.DESCENDING) { direction = -1; } this.caseInsensitive = caseInsensitive; } public int compare(Object obj1, Object obj2) { MyOrderComponentQuestionsVo voObj1 = (MyOrderComponentQuestionsVo)obj1; MyOrderComponentQuestionsVo voObj2 = (MyOrderComponentQuestionsVo)obj2; return direction*(voObj1.compareTo(voObj2, this.caseInsensitive)); } public boolean equals(Object obj) { return false; } } public ims.ocrr.vo.beans.MyOrderComponentQuestionsVoBean[] getBeanCollection() { return getBeanCollectionArray(); } public ims.ocrr.vo.beans.MyOrderComponentQuestionsVoBean[] getBeanCollectionArray() { ims.ocrr.vo.beans.MyOrderComponentQuestionsVoBean[] result = new ims.ocrr.vo.beans.MyOrderComponentQuestionsVoBean[col.size()]; for(int i = 0; i < col.size(); i++) { MyOrderComponentQuestionsVo vo = ((MyOrderComponentQuestionsVo)col.get(i)); result[i] = (ims.ocrr.vo.beans.MyOrderComponentQuestionsVoBean)vo.getBean(); } return result; } public static MyOrderComponentQuestionsVoCollection buildFromBeanCollection(java.util.Collection beans) { MyOrderComponentQuestionsVoCollection coll = new MyOrderComponentQuestionsVoCollection(); if(beans == null) return coll; java.util.Iterator iter = beans.iterator(); while (iter.hasNext()) { coll.add(((ims.ocrr.vo.beans.MyOrderComponentQuestionsVoBean)iter.next()).buildVo()); } return coll; } public static MyOrderComponentQuestionsVoCollection buildFromBeanCollection(ims.ocrr.vo.beans.MyOrderComponentQuestionsVoBean[] beans) { MyOrderComponentQuestionsVoCollection coll = new MyOrderComponentQuestionsVoCollection(); if(beans == null) return coll; for(int x = 0; x < beans.length; x++) { coll.add(beans[x].buildVo()); } return coll; } }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/ocrr/vo/MyOrderComponentQuestionsVoCollection.java
Java
agpl-3.0
8,715
""" Test the behavior of split_mongo/MongoConnection """ from __future__ import absolute_import import unittest from mock import patch from xmodule.exceptions import HeartbeatFailure from xmodule.modulestore.split_mongo.mongo_connection import MongoConnection class TestHeartbeatFailureException(unittest.TestCase): """ Test that a heartbeat failure is thrown at the appropriate times """ @patch('pymongo.MongoClient') @patch('pymongo.database.Database') def test_heartbeat_raises_exception_when_connection_alive_is_false(self, *calls): # pylint: disable=W0613 with patch('mongodb_proxy.MongoProxy') as mock_proxy: mock_proxy.return_value.alive.return_value = False useless_conn = MongoConnection('useless', 'useless', 'useless') with self.assertRaises(HeartbeatFailure): useless_conn.heartbeat()
ESOedX/edx-platform
common/lib/xmodule/xmodule/modulestore/tests/test_split_mongo_mongo_connection.py
Python
agpl-3.0
888
/** * ownCloud - fuel * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @copyright Christoph Wurst 2015 */ define(function (require) { 'use strinct'; var VehicleView = require('views/vehicle'), Marionette = require('marionette'); return Marionette.CollectionView.extend({ tagName: 'ul', childView: VehicleView, initialize: function (options) { options = options || {}; this.listenTo(this.collection, 'change', this.render); } }); });
ChristophWurst/fuel
js/views/vehiclelist.js
JavaScript
agpl-3.0
586
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.vo; /** * Linked to core.patient.NationalHealthCover business object (ID: 1001100005). */ public class NationalHealthCoverVo extends ims.core.patient.vo.NationalHealthCoverRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public NationalHealthCoverVo() { } public NationalHealthCoverVo(Integer id, int version) { super(id, version); } public NationalHealthCoverVo(ims.core.vo.beans.NationalHealthCoverVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.medicalcardno = bean.getMedicalCardNo(); this.healthactcategory = bean.getHealthActCategory() == null ? null : ims.core.vo.lookups.PersonHealthActCategory.buildLookup(bean.getHealthActCategory()); this.ehicnumber = bean.getEHICNumber(); this.ehicexpirydate = bean.getEHICExpiryDate() == null ? null : bean.getEHICExpiryDate().buildPartialDate(); this.ehiccountry = bean.getEHICCountry() == null ? null : ims.core.vo.lookups.Country.buildLookup(bean.getEHICCountry()); this.ehicinstitution = bean.getEHICInstitution(); this.medicalcardproved = bean.getMedicalCardProved() == null ? null : ims.core.vo.lookups.YesNo.buildLookup(bean.getMedicalCardProved()); this.eligibilityproof = bean.getEligibilityProof(); this.medicalcardexpirydate = bean.getMedicalCardExpiryDate() == null ? null : bean.getMedicalCardExpiryDate().buildPartialDate(); this.ehicinstitutioncode = bean.getEHICInstitutionCode() == null ? null : ims.core.vo.lookups.Institution.buildLookup(bean.getEHICInstitutionCode()); this.eligibility = bean.getEligibility() == null ? null : ims.core.vo.lookups.Eligibility.buildLookup(bean.getEligibility()); } public void populate(ims.vo.ValueObjectBeanMap map, ims.core.vo.beans.NationalHealthCoverVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.medicalcardno = bean.getMedicalCardNo(); this.healthactcategory = bean.getHealthActCategory() == null ? null : ims.core.vo.lookups.PersonHealthActCategory.buildLookup(bean.getHealthActCategory()); this.ehicnumber = bean.getEHICNumber(); this.ehicexpirydate = bean.getEHICExpiryDate() == null ? null : bean.getEHICExpiryDate().buildPartialDate(); this.ehiccountry = bean.getEHICCountry() == null ? null : ims.core.vo.lookups.Country.buildLookup(bean.getEHICCountry()); this.ehicinstitution = bean.getEHICInstitution(); this.medicalcardproved = bean.getMedicalCardProved() == null ? null : ims.core.vo.lookups.YesNo.buildLookup(bean.getMedicalCardProved()); this.eligibilityproof = bean.getEligibilityProof(); this.medicalcardexpirydate = bean.getMedicalCardExpiryDate() == null ? null : bean.getMedicalCardExpiryDate().buildPartialDate(); this.ehicinstitutioncode = bean.getEHICInstitutionCode() == null ? null : ims.core.vo.lookups.Institution.buildLookup(bean.getEHICInstitutionCode()); this.eligibility = bean.getEligibility() == null ? null : ims.core.vo.lookups.Eligibility.buildLookup(bean.getEligibility()); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.core.vo.beans.NationalHealthCoverVoBean bean = null; if(map != null) bean = (ims.core.vo.beans.NationalHealthCoverVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.core.vo.beans.NationalHealthCoverVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("MEDICALCARDNO")) return getMedicalCardNo(); if(fieldName.equals("HEALTHACTCATEGORY")) return getHealthActCategory(); if(fieldName.equals("EHICNUMBER")) return getEHICNumber(); if(fieldName.equals("EHICEXPIRYDATE")) return getEHICExpiryDate(); if(fieldName.equals("EHICCOUNTRY")) return getEHICCountry(); if(fieldName.equals("EHICINSTITUTION")) return getEHICInstitution(); if(fieldName.equals("MEDICALCARDPROVED")) return getMedicalCardProved(); if(fieldName.equals("ELIGIBILITYPROOF")) return getEligibilityProof(); if(fieldName.equals("MEDICALCARDEXPIRYDATE")) return getMedicalCardExpiryDate(); if(fieldName.equals("EHICINSTITUTIONCODE")) return getEHICInstitutionCode(); if(fieldName.equals("ELIGIBILITY")) return getEligibility(); return super.getFieldValueByFieldName(fieldName); } public boolean getMedicalCardNoIsNotNull() { return this.medicalcardno != null; } public String getMedicalCardNo() { return this.medicalcardno; } public static int getMedicalCardNoMaxLength() { return 50; } public void setMedicalCardNo(String value) { this.isValidated = false; this.medicalcardno = value; } public boolean getHealthActCategoryIsNotNull() { return this.healthactcategory != null; } public ims.core.vo.lookups.PersonHealthActCategory getHealthActCategory() { return this.healthactcategory; } public void setHealthActCategory(ims.core.vo.lookups.PersonHealthActCategory value) { this.isValidated = false; this.healthactcategory = value; } public boolean getEHICNumberIsNotNull() { return this.ehicnumber != null; } public String getEHICNumber() { return this.ehicnumber; } public static int getEHICNumberMaxLength() { return 20; } public void setEHICNumber(String value) { this.isValidated = false; this.ehicnumber = value; } public boolean getEHICExpiryDateIsNotNull() { return this.ehicexpirydate != null; } public ims.framework.utils.PartialDate getEHICExpiryDate() { return this.ehicexpirydate; } public void setEHICExpiryDate(ims.framework.utils.PartialDate value) { this.isValidated = false; this.ehicexpirydate = value; } public boolean getEHICCountryIsNotNull() { return this.ehiccountry != null; } public ims.core.vo.lookups.Country getEHICCountry() { return this.ehiccountry; } public void setEHICCountry(ims.core.vo.lookups.Country value) { this.isValidated = false; this.ehiccountry = value; } public boolean getEHICInstitutionIsNotNull() { return this.ehicinstitution != null; } public String getEHICInstitution() { return this.ehicinstitution; } public static int getEHICInstitutionMaxLength() { return 255; } public void setEHICInstitution(String value) { this.isValidated = false; this.ehicinstitution = value; } public boolean getMedicalCardProvedIsNotNull() { return this.medicalcardproved != null; } public ims.core.vo.lookups.YesNo getMedicalCardProved() { return this.medicalcardproved; } public void setMedicalCardProved(ims.core.vo.lookups.YesNo value) { this.isValidated = false; this.medicalcardproved = value; } public boolean getEligibilityProofIsNotNull() { return this.eligibilityproof != null; } public String getEligibilityProof() { return this.eligibilityproof; } public static int getEligibilityProofMaxLength() { return 255; } public void setEligibilityProof(String value) { this.isValidated = false; this.eligibilityproof = value; } public boolean getMedicalCardExpiryDateIsNotNull() { return this.medicalcardexpirydate != null; } public ims.framework.utils.PartialDate getMedicalCardExpiryDate() { return this.medicalcardexpirydate; } public void setMedicalCardExpiryDate(ims.framework.utils.PartialDate value) { this.isValidated = false; this.medicalcardexpirydate = value; } public boolean getEHICInstitutionCodeIsNotNull() { return this.ehicinstitutioncode != null; } public ims.core.vo.lookups.Institution getEHICInstitutionCode() { return this.ehicinstitutioncode; } public void setEHICInstitutionCode(ims.core.vo.lookups.Institution value) { this.isValidated = false; this.ehicinstitutioncode = value; } public boolean getEligibilityIsNotNull() { return this.eligibility != null; } public ims.core.vo.lookups.Eligibility getEligibility() { return this.eligibility; } public void setEligibility(ims.core.vo.lookups.Eligibility value) { this.isValidated = false; this.eligibility = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } if(this.medicalcardno != null) if(this.medicalcardno.length() > 50) listOfErrors.add("The length of the field [medicalcardno] in the value object [ims.core.vo.NationalHealthCoverVo] is too big. It should be less or equal to 50"); if(this.ehicnumber != null) if(this.ehicnumber.length() > 20) listOfErrors.add("The length of the field [ehicnumber] in the value object [ims.core.vo.NationalHealthCoverVo] is too big. It should be less or equal to 20"); if(this.ehicinstitution != null) if(this.ehicinstitution.length() > 255) listOfErrors.add("The length of the field [ehicinstitution] in the value object [ims.core.vo.NationalHealthCoverVo] is too big. It should be less or equal to 255"); if(this.eligibilityproof != null) if(this.eligibilityproof.length() > 255) listOfErrors.add("The length of the field [eligibilityproof] in the value object [ims.core.vo.NationalHealthCoverVo] is too big. It should be less or equal to 255"); int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; NationalHealthCoverVo clone = new NationalHealthCoverVo(this.id, this.version); clone.medicalcardno = this.medicalcardno; if(this.healthactcategory == null) clone.healthactcategory = null; else clone.healthactcategory = (ims.core.vo.lookups.PersonHealthActCategory)this.healthactcategory.clone(); clone.ehicnumber = this.ehicnumber; if(this.ehicexpirydate == null) clone.ehicexpirydate = null; else clone.ehicexpirydate = (ims.framework.utils.PartialDate)this.ehicexpirydate.clone(); if(this.ehiccountry == null) clone.ehiccountry = null; else clone.ehiccountry = (ims.core.vo.lookups.Country)this.ehiccountry.clone(); clone.ehicinstitution = this.ehicinstitution; if(this.medicalcardproved == null) clone.medicalcardproved = null; else clone.medicalcardproved = (ims.core.vo.lookups.YesNo)this.medicalcardproved.clone(); clone.eligibilityproof = this.eligibilityproof; if(this.medicalcardexpirydate == null) clone.medicalcardexpirydate = null; else clone.medicalcardexpirydate = (ims.framework.utils.PartialDate)this.medicalcardexpirydate.clone(); if(this.ehicinstitutioncode == null) clone.ehicinstitutioncode = null; else clone.ehicinstitutioncode = (ims.core.vo.lookups.Institution)this.ehicinstitutioncode.clone(); if(this.eligibility == null) clone.eligibility = null; else clone.eligibility = (ims.core.vo.lookups.Eligibility)this.eligibility.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(NationalHealthCoverVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A NationalHealthCoverVo object cannot be compared an Object of type " + obj.getClass().getName()); } if (this.id == null) return 1; if (((NationalHealthCoverVo)obj).getBoId() == null) return -1; return this.id.compareTo(((NationalHealthCoverVo)obj).getBoId()); } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.medicalcardno != null) count++; if(this.healthactcategory != null) count++; if(this.ehicnumber != null) count++; if(this.ehicexpirydate != null) count++; if(this.ehiccountry != null) count++; if(this.ehicinstitution != null) count++; if(this.medicalcardproved != null) count++; if(this.eligibilityproof != null) count++; if(this.medicalcardexpirydate != null) count++; if(this.ehicinstitutioncode != null) count++; if(this.eligibility != null) count++; return count; } public int countValueObjectFields() { return 11; } protected String medicalcardno; protected ims.core.vo.lookups.PersonHealthActCategory healthactcategory; protected String ehicnumber; protected ims.framework.utils.PartialDate ehicexpirydate; protected ims.core.vo.lookups.Country ehiccountry; protected String ehicinstitution; protected ims.core.vo.lookups.YesNo medicalcardproved; protected String eligibilityproof; protected ims.framework.utils.PartialDate medicalcardexpirydate; protected ims.core.vo.lookups.Institution ehicinstitutioncode; protected ims.core.vo.lookups.Eligibility eligibility; private boolean isValidated = false; private boolean isBusy = false; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/core/vo/NationalHealthCoverVo.java
Java
agpl-3.0
16,391
<?php if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd. * Copyright (C) 2011 - 2016 Salesagility Ltd. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not * reasonably feasible for technical reasons, the Appropriate Legal Notices must * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM". ********************************************************************************/ $layout_defs['Contacts'] = array( // list of what Subpanels to show in the DetailView 'subpanel_setup' => array( 'activities' => array( 'order' => 10, 'sort_order' => 'desc', 'sort_by' => 'date_start', 'title_key' => 'LBL_ACTIVITIES_SUBPANEL_TITLE', 'type' => 'collection', 'subpanel_name' => 'activities', //this values is not associated with a physical file. 'module' => 'Activities', 'top_buttons' => array( array('widget_class' => 'SubPanelTopCreateTaskButton'), array('widget_class' => 'SubPanelTopScheduleMeetingButton'), array('widget_class' => 'SubPanelTopScheduleCallButton'), array('widget_class' => 'SubPanelTopComposeEmailButton'), ), 'collection_list' => array( 'tasks' => array( 'module' => 'Tasks', 'subpanel_name' => 'ForActivities', 'get_subpanel_data' => 'tasks', ), 'tasks_parent' => array( 'module' => 'Tasks', 'subpanel_name' => 'ForActivities', 'get_subpanel_data' => 'tasks_parent', ), 'meetings' => array( 'module' => 'Meetings', 'subpanel_name' => 'ForActivities', 'get_subpanel_data' => 'meetings', ), 'calls' => array( 'module' => 'Calls', 'subpanel_name' => 'ForActivities', 'get_subpanel_data' => 'calls', ), ) ), 'history' => array( 'order' => 20, 'sort_order' => 'desc', 'sort_by' => 'date_entered', 'title_key' => 'LBL_HISTORY_SUBPANEL_TITLE', 'type' => 'collection', 'subpanel_name' => 'history', //this values is not associated with a physical file. 'module' => 'History', 'top_buttons' => array( array('widget_class' => 'SubPanelTopCreateNoteButton'), array('widget_class' => 'SubPanelTopArchiveEmailButton'), array('widget_class' => 'SubPanelTopSummaryButton'), array('widget_class' => 'SubPanelTopFilterButton'), ), 'collection_list' => array( 'tasks' => array( 'module' => 'Tasks', 'subpanel_name' => 'ForHistory', 'get_subpanel_data' => 'tasks', ), 'tasks_parent' => array( 'module' => 'Tasks', 'subpanel_name' => 'ForHistory', 'get_subpanel_data' => 'tasks_parent', ), 'meetings' => array( 'module' => 'Meetings', 'subpanel_name' => 'ForHistory', 'get_subpanel_data' => 'meetings', ), 'calls' => array( 'module' => 'Calls', 'subpanel_name' => 'ForHistory', 'get_subpanel_data' => 'calls', ), 'notes' => array( 'module' => 'Notes', 'subpanel_name' => 'ForHistory', 'get_subpanel_data' => 'notes', ), 'emails' => array( 'module' => 'Emails', 'subpanel_name' => 'ForHistory', 'get_subpanel_data' => 'emails', ), 'linkedemails' => array( 'module' => 'Emails', 'subpanel_name' => 'ForUnlinkedEmailHistory', 'get_subpanel_data' => 'function:get_unlinked_email_query', 'generate_select' => true, 'function_parameters' => array('return_as_array' => 'true'), ), ), 'searchdefs' => array( 'collection' => array( 'name' => 'collection', 'label' => 'LBL_COLLECTION_TYPE', 'type' => 'enum', 'options' => $GLOBALS['app_list_strings']['collection_temp_list'], 'default' => true, 'width' => '10%', ), 'name' => array( 'name' => 'name', 'default' => true, 'width' => '10%', ), 'current_user_only' => array( 'name' => 'current_user_only', 'label' => 'LBL_CURRENT_USER_FILTER', 'type' => 'bool', 'default' => true, 'width' => '10%', ), 'date_modified' => array( 'name' => 'date_modified', 'default' => true, 'width' => '10%', ), ), ), 'documents' => array( 'order' => 25, 'module' => 'Documents', 'subpanel_name' => 'default', 'sort_order' => 'asc', 'sort_by' => 'id', 'title_key' => 'LBL_DOCUMENTS_SUBPANEL_TITLE', 'get_subpanel_data' => 'documents', 'top_buttons' => array( 0 => array( 'widget_class' => 'SubPanelTopButtonQuickCreate', ), 1 => array( 'widget_class' => 'SubPanelTopSelectButton', 'mode' => 'MultiSelect', ), ), ), 'leads' => array( 'order' => 60, 'module' => 'Leads', 'sort_order' => 'asc', 'sort_by' => 'last_name, first_name', 'subpanel_name' => 'default', 'get_subpanel_data' => 'leads', 'add_subpanel_data' => 'lead_id', 'title_key' => 'LBL_LEADS_SUBPANEL_TITLE', 'top_buttons' => array( array('widget_class' => 'SubPanelTopCreateLeadNameButton'), array('widget_class' => 'SubPanelTopSelectButton', 'popup_module' => 'Opportunities', 'mode' => 'MultiSelect', ), ), ), 'opportunities' => array( 'order' => 30, 'module' => 'Opportunities', 'sort_order' => 'desc', 'sort_by' => 'date_closed', 'subpanel_name' => 'default', 'get_subpanel_data' => 'opportunities', 'add_subpanel_data' => 'opportunity_id', 'title_key' => 'LBL_OPPORTUNITIES_SUBPANEL_TITLE', 'top_buttons' => array( array('widget_class' => 'SubPanelTopButtonQuickCreate'), array('widget_class' => 'SubPanelTopSelectButton', 'mode' => 'MultiSelect') ), ), 'cases' => array( 'order' => 80, 'sort_order' => 'desc', 'sort_by' => 'case_number', 'module' => 'Cases', 'subpanel_name' => 'default', 'get_subpanel_data' => 'cases', 'add_subpanel_data' => 'case_id', 'title_key' => 'LBL_CASES_SUBPANEL_TITLE', 'top_buttons' => array( array('widget_class' => 'SubPanelTopButtonQuickCreate'), array('widget_class' => 'SubPanelTopSelectButton', 'mode' => 'MultiSelect') ), ), 'bugs' => array( 'order' => 90, 'module' => 'Bugs', 'sort_order' => 'desc', 'sort_by' => 'bug_number', 'subpanel_name' => 'default', 'get_subpanel_data' => 'bugs', 'add_subpanel_data' => 'bug_id', 'title_key' => 'LBL_BUGS_SUBPANEL_TITLE', 'top_buttons' => array( array('widget_class' => 'SubPanelTopButtonQuickCreate'), array('widget_class' => 'SubPanelTopSelectButton', 'mode' => 'MultiSelect') ), ), 'contacts' => array( 'order' => 100, 'module' => 'Contacts', 'sort_order' => 'asc', 'sort_by' => 'last_name, first_name', 'subpanel_name' => 'ForContacts', 'get_subpanel_data' => 'direct_reports', 'add_subpanel_data' => 'contact_id', 'title_key' => 'LBL_DIRECT_REPORTS_SUBPANEL_TITLE', 'top_buttons' => array( array('widget_class' => 'SubPanelTopButtonQuickCreate'), array('widget_class' => 'SubPanelTopSelectButton', 'mode' => 'MultiSelect') ), ), 'project' => array( 'order' => 110, 'module' => 'Project', 'sort_order' => 'asc', 'sort_by' => 'name', 'get_subpanel_data' => 'project', 'subpanel_name' => 'default', 'title_key' => 'LBL_PROJECTS_SUBPANEL_TITLE', 'top_buttons' => array( array('widget_class' => 'SubPanelTopButtonQuickCreate'), array('widget_class' => 'SubPanelTopSelectButton', 'mode' => 'MultiSelect'), ), ), 'campaigns' => array( 'order' => 70, 'module' => 'CampaignLog', 'sort_order' => 'desc', 'sort_by' => 'activity_date', 'get_subpanel_data' => 'campaigns', 'subpanel_name' => 'ForTargets', 'title_key' => 'LBL_CAMPAIGN_LIST_SUBPANEL_TITLE', ), 'contact_aos_quotes' => array( 'order' => 101, 'module' => 'AOS_Quotes', 'subpanel_name' => 'default', 'sort_order' => 'asc', 'sort_by' => 'id', 'title_key' => 'AOS_Quotes', 'get_subpanel_data' => 'aos_quotes', ), 'contact_aos_invoices' => array( 'order' => 102, 'module' => 'AOS_Invoices', 'subpanel_name' => 'default', 'sort_order' => 'asc', 'sort_by' => 'id', 'title_key' => 'AOS_Invoices', 'get_subpanel_data' => 'aos_invoices', ), 'contact_aos_contracts' => array( 'order' => 103, 'module' => 'AOS_Contracts', 'subpanel_name' => 'default', 'sort_order' => 'asc', 'sort_by' => 'id', 'title_key' => 'AOS_Contracts', 'get_subpanel_data' => 'aos_contracts', ), 'fp_events_contacts' => array( 'order' => 104, 'module' => 'FP_events', 'subpanel_name' => 'default', 'sort_order' => 'asc', 'sort_by' => 'id', 'title_key' => 'LBL_FP_EVENTS_CONTACTS_FROM_FP_EVENTS_TITLE', 'get_subpanel_data' => 'fp_events_contacts', 'top_buttons' => array( 0 => array( 'widget_class' => 'SubPanelTopButtonQuickCreate', ), 1 => array( 'widget_class' => 'SubPanelTopSelectButton', 'mode' => 'MultiSelect', ), ), ), 'securitygroups' => array( 'top_buttons' => array(array('widget_class' => 'SubPanelTopSelectButton', 'popup_module' => 'SecurityGroups', 'mode' => 'MultiSelect'),), 'order' => 900, 'sort_by' => 'name', 'sort_order' => 'asc', 'module' => 'SecurityGroups', 'refresh_page' => 1, 'subpanel_name' => 'default', 'get_subpanel_data' => 'SecurityGroups', 'add_subpanel_data' => 'securitygroup_id', 'title_key' => 'LBL_SECURITYGROUPS_SUBPANEL_TITLE', ), ), );
noelhunter/SuiteCRM
modules/Contacts/metadata/subpaneldefs.php
PHP
agpl-3.0
14,653
/* * This file is part of the Sofia-SIP package * * Copyright (C) 2005 Nokia Corporation. * * Contact: Pekka Pessi <pekka.pessi@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ /**@CFILE nta.c * @brief Sofia SIP Transaction API implementation * * This source file has been divided into sections as follows: * 1) agent * 2) tport handling * 3) dispatching messages received from network * 4) message creation and message utility functions * 5) stateless operation * 6) dialogs (legs) * 7) server transactions (incoming) * 8) client transactions (outgoing) * 9) resolving URLs for client transactions * 10) 100rel reliable responses (reliable) * 11) SigComp handling and public transport interface * * @author Pekka Pessi <Pekka.Pessi@nokia.com> * * @date Created: Tue Jun 13 02:57:51 2000 ppessi * * @sa * @RFC3261, @RFC4320 */ #include "config.h" #include <sofia-sip/su_string.h> /** @internal SU message argument structure type */ #define SU_MSG_ARG_T union sm_arg_u /** @internal SU timer argument pointer type */ #define SU_TIMER_ARG_T struct nta_agent_s #include <sofia-sip/su_alloc.h> #include <sofia-sip/su.h> #include <sofia-sip/su_time.h> #include <sofia-sip/su_wait.h> #include <sofia-sip/su_tagarg.h> #include <sofia-sip/base64.h> #include <sofia-sip/su_uniqueid.h> #include <sofia-sip/sip.h> #include <sofia-sip/sip_header.h> #include <sofia-sip/sip_util.h> #include <sofia-sip/sip_status.h> #include <sofia-sip/hostdomain.h> #include <sofia-sip/url_tag.h> #include <sofia-sip/msg_addr.h> #include <sofia-sip/msg_parser.h> #include <sofia-sip/htable.h> /* Resolver context type */ #define SRES_CONTEXT_T nta_outgoing_t /* We are customer of tport_t */ #define TP_AGENT_T nta_agent_t #define TP_MAGIC_T sip_via_t #define TP_CLIENT_T nta_outgoing_t #include "nta_internal.h" #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <assert.h> #include <limits.h> #include <errno.h> /* From AM_INIT/AC_INIT in our "config.h" */ char const nta_version[] = PACKAGE_VERSION; #if HAVE_FUNC #elif HAVE_FUNCTION #define __func__ __FUNCTION__ #else static char const __func__[] = "nta"; #endif #define NONE ((void *)(intptr_t)-1) /* ------------------------------------------------------------------------- */ /** Resolving order */ enum nta_res_order_e { nta_res_ip6_ip4, nta_res_ip4_ip6, nta_res_ip6_only, nta_res_ip4_only }; HTABLE_DECLARE_WITH(leg_htable, lht, nta_leg_t, size_t, hash_value_t); HTABLE_DECLARE_WITH(outgoing_htable, oht, nta_outgoing_t, size_t, hash_value_t); HTABLE_DECLARE_WITH(incoming_htable, iht, nta_incoming_t, size_t, hash_value_t); typedef struct outgoing_queue_t { nta_outgoing_t **q_tail; nta_outgoing_t *q_head; size_t q_length; unsigned q_timeout; } outgoing_queue_t; typedef struct incoming_queue_t { nta_incoming_t **q_tail; nta_incoming_t *q_head; size_t q_length; unsigned q_timeout; } incoming_queue_t; struct nta_agent_s { su_home_t sa_home[1]; su_root_t *sa_root; su_timer_t *sa_timer; nta_agent_magic_t *sa_magic; nta_message_f *sa_callback; nta_update_magic_t *sa_update_magic; nta_update_tport_f *sa_update_tport; su_time_t sa_now; /**< Timestamp in microsecond resolution. */ uint32_t sa_next; /**< Timestamp for next agent_timer. */ uint32_t sa_millisec; /**< Timestamp in milliseconds. */ uint32_t sa_cseq; msg_mclass_t const *sa_mclass; uint32_t sa_flags; /**< SIP message flags */ unsigned sa_preload; /**< Memory preload for SIP messages. */ tport_t *sa_tports; sip_contact_t *sa_contact; sip_via_t *sa_vias; /**< @Via headers for all transports */ sip_via_t *sa_public_vias; /**< @Vias for public transports */ sip_contact_t *sa_aliases;/**< List of aliases for agent */ uint64_t sa_branch; /**< Generator for branch parameters */ uint64_t sa_tags; /**< Generator for tag parameters */ #if HAVE_SOFIA_SRESOLV sres_resolver_t *sa_resolver; /**< DNS resolver */ enum nta_res_order_e sa_res_order; /** Resolving order (AAAA/A) */ #endif url_t *sa_default_proxy; /**< Default outbound proxy */ unsigned sa_bad_req_mask; /**< Request error mask */ unsigned sa_bad_resp_mask; /**< Response error mask */ usize_t sa_maxsize; /**< Maximum size of incoming messages */ usize_t sa_max_proceeding; /**< Maximum size of proceeding queue */ unsigned sa_udp_mtu; /**< Maximum size of outgoing UDP requests */ unsigned sa_t1; /**< SIP T1 - initial retransmit interval (500 ms) */ unsigned sa_t2; /**< SIP T2 - maximum retransmit interval (4000 ms) */ unsigned sa_t4; /**< SIP T4 - clear message time (5000 ms) */ unsigned sa_t1x64; /**< SIP T1X64 - transaction lifetime (32 s) */ unsigned sa_progress; /**< Progress timer. Interval between retransmitting provisional responses. */ unsigned sa_timer_c; /**< SIP timer C. Maximum interval between receiving provisional responses. */ unsigned sa_graylist; /**< Graylisting period */ unsigned sa_blacklist; /**< Blacklisting period */ unsigned sa_drop_prob : 10; /**< NTA is used to test packet drop */ unsigned sa_is_a_uas : 1; /**< NTA is acting as an User Agent server */ unsigned sa_is_stateless : 1; /**< Process requests statelessly * unless they match existing dialog. */ unsigned sa_user_via:1; /**< Let application provide @Via headers */ unsigned sa_extra_100:1; /**< Allow NTA to return "100 Trying" response * even if application has not responded. */ unsigned sa_pass_100:1; /**< Pass the "100 Trying" * provisional responses to the application */ unsigned sa_timeout_408:1; /**< A "408 Request Timeout" message * is generated when outgoing request expires. */ unsigned sa_pass_408:1; /**< A "408 Request Timeout" responses * are passed to client. */ unsigned sa_merge_482 : 1; /**< A "482 Request Merged" response is returned * to merged requests. */ unsigned sa_cancel_2543 : 1; /**< Send a CANCEL to an INVITE without * waiting for an provisional response. */ unsigned sa_cancel_487 : 1; /**< Return 487 response automatically when * a CANCEL is received. */ unsigned sa_invite_100rel:1; /**< Include 100rel in INVITE requests. */ unsigned sa_timestamp : 1; /**< Insert @Timestamp in requests. */ unsigned sa_tport_ip4 : 1; /**< Transports support IPv4. */ unsigned sa_tport_ip6 : 1; /**< Transports support IPv6. */ unsigned sa_tport_udp : 1; /**< Transports support UDP. */ unsigned sa_tport_tcp : 1; /**< Transports support TCP. */ unsigned sa_tport_sctp : 1; /**< Transports support SCTP. */ unsigned sa_tport_tls : 1; /**< Transports support TLS. */ unsigned sa_use_naptr : 1; /**< Use NAPTR lookup */ unsigned sa_use_srv : 1; /**< Use SRV lookup */ unsigned sa_tport_threadpool:1; /**< Transports use threadpool */ unsigned sa_rport:1; /**< Use rport at client */ unsigned sa_server_rport:2; /**< Use rport at server */ unsigned sa_tcp_rport:1; /**< Use rport with tcp, too */ unsigned sa_tls_rport:1; /**< Use rport with tls, too */ unsigned sa_auto_comp:1; /**< Automatically create compartments */ unsigned sa_in_timer:1; /**< Set when executing timers */ unsigned sa_use_timer_c:1; /**< Application has set value for timer C */ unsigned :0; #if HAVE_SMIME sm_object_t *sa_smime; #else void *sa_smime; #endif /** @MaxForwards */ sip_max_forwards_t sa_max_forwards[1]; /** Name of SigComp algorithm */ char const *sa_algorithm; /** Options for SigComp. */ char const *sa_sigcomp_options; char const* const *sa_sigcomp_option_list; char const *sa_sigcomp_option_free; nta_compressor_t *sa_compressor; /* Statistics */ struct { usize_t as_recv_msg; usize_t as_recv_request; usize_t as_recv_response; usize_t as_bad_message; usize_t as_bad_request; usize_t as_bad_response; usize_t as_drop_request; usize_t as_drop_response; usize_t as_client_tr; usize_t as_server_tr; usize_t as_dialog_tr; usize_t as_acked_tr; usize_t as_canceled_tr; usize_t as_trless_request; usize_t as_trless_to_tr; usize_t as_trless_response; usize_t as_trless_200; usize_t as_merged_request; usize_t as_sent_msg; usize_t as_sent_request; usize_t as_sent_response; usize_t as_retry_request; usize_t as_retry_response; usize_t as_recv_retry; usize_t as_tout_request; usize_t as_tout_response; } sa_stats[1]; /** Hash of dialogs. */ leg_htable_t sa_dialogs[1]; /** Default leg */ nta_leg_t *sa_default_leg; /** Hash of legs without dialogs. */ leg_htable_t sa_defaults[1]; /** Hash table for outgoing transactions */ outgoing_htable_t sa_outgoing[1]; nta_outgoing_t *sa_default_outgoing; /** Hash table for incoming transactions */ incoming_htable_t sa_incoming[1]; nta_incoming_t *sa_default_incoming; /* Queues (states) for outgoing client transactions */ struct { /** Queue for retrying client transactions */ nta_outgoing_t *re_list; nta_outgoing_t **re_t1; /**< Special place for T1 timer */ size_t re_length; /**< Length of sa_out.re_list */ outgoing_queue_t delayed[1]; outgoing_queue_t resolving[1]; outgoing_queue_t trying[1]; /* Timer F / Timer E */ outgoing_queue_t completed[1]; /* Timer K */ outgoing_queue_t terminated[1]; /* Special queues (states) for outgoing INVITE transactions */ outgoing_queue_t inv_calling[1]; /* Timer B/A */ outgoing_queue_t inv_proceeding[1]; /* Timer C */ outgoing_queue_t inv_completed[1]; /* Timer D */ /* Temporary queue for transactions waiting to be freed */ outgoing_queue_t *free; } sa_out; /* Queues (states) for incoming server transactions */ struct { /** Queue for retransmitting response of server transactions */ nta_incoming_t *re_list; nta_incoming_t **re_t1; /**< Special place for T1 timer */ size_t re_length; /**< Length of sa_in.re_list */ incoming_queue_t proceeding[1]; /**< Request received */ incoming_queue_t preliminary[1]; /**< 100rel sent */ incoming_queue_t completed[1]; /**< Final answer sent (non-invite). */ incoming_queue_t inv_completed[1]; /**< Final answer sent (INVITE). */ incoming_queue_t inv_confirmed[1]; /**< Final answer sent, ACK recvd. */ incoming_queue_t terminated[1]; /**< Terminated, ready to free. */ incoming_queue_t final_failed[1]; } sa_in; /* Special task for freeing memory */ su_clone_r sa_terminator; }; struct nta_leg_s { su_home_t leg_home[1]; hash_value_t leg_hash; unsigned leg_dialog : 1; unsigned leg_stateless : 1; /**< Process requests statelessly */ #ifdef NTA_STRICT_ROUTING unsigned leg_contact_set : 1; #else unsigned leg_loose_route : 1; /**< Topmost route in set is LR */ #endif unsigned leg_route_set : 1; /**< Route set has been saved */ unsigned leg_local_is_to : 1; /**< Backwards-compatibility. */ unsigned leg_tagged : 1; /**< Tagged after creation. * * Request missing @To tag matches * a tagged leg even after tagging. */ unsigned:0; nta_request_f *leg_callback; nta_leg_magic_t *leg_magic; nta_agent_t *leg_agent; url_t const *leg_url; /**< Match incoming requests. */ char const *leg_method; /**< Match incoming requests. */ uint32_t leg_seq; /**< Sequence number for next transaction */ uint32_t leg_rseq; /**< Remote sequence number */ sip_call_id_t *leg_id; /**< Call ID */ sip_from_t *leg_remote; /**< Remote address (@To/@From) */ sip_to_t *leg_local; /**< Local address (@From/@To) */ sip_route_t *leg_route; /**< @Route for outgoing requests. */ sip_contact_t *leg_target; /**< Remote destination (from @Contact). */ }; struct nta_incoming_s { su_home_t *irq_home; hash_value_t irq_hash; nta_agent_t *irq_agent; nta_ack_cancel_f *irq_callback; nta_incoming_magic_t *irq_magic; /* Timeout/state queue */ nta_incoming_t **irq_prev; nta_incoming_t *irq_next; incoming_queue_t *irq_queue; /* Retry queue */ nta_incoming_t **irq_rprev; nta_incoming_t *irq_rnext; sip_method_t irq_method; sip_request_t *irq_rq; sip_from_t *irq_from; sip_to_t *irq_to; char const *irq_tag; sip_cseq_t *irq_cseq; sip_call_id_t *irq_call_id; sip_via_t *irq_via; sip_record_route_t *irq_record_route; char const *irq_branch; uint32_t irq_rseq; sip_timestamp_t *irq_timestamp; su_time_t irq_received; uint32_t irq_timeout; /**< Timer H, I, J */ uint32_t irq_retry; /**< Timer G */ unsigned short irq_interval; /**< Next timer */ short irq_status; unsigned irq_retries:8; /**< Number of retries. * Disable SigComp if too many retries. */ unsigned irq_default:1; /**< Default transaction */ unsigned irq_canceled:1; /**< Transaction is canceled */ unsigned irq_completed:1; /**< Transaction is completed */ unsigned irq_confirmed:1; /**< Response has been acked */ unsigned irq_terminated:1; /**< Transaction is terminated */ unsigned irq_final_failed:1; /**< Sending final response failed */ unsigned irq_destroyed :1; /**< Transaction is destroyed */ unsigned irq_in_callback:1; /**< Callback is being invoked */ unsigned irq_reliable_tp:1; /**< Transport is reliable */ unsigned irq_sigcomp_zap:1; /**< Reset SigComp */ unsigned irq_must_100rel:1; /**< 100rel is required */ unsigned irq_extra_100:1; /**< 100 Trying should be sent */ unsigned irq_tag_set:1; /**< Tag is not from request */ unsigned :0; tp_name_t irq_tpn[1]; tport_t *irq_tport; struct sigcomp_compartment *irq_cc; msg_t *irq_request; msg_t *irq_request2; /**< ACK/CANCEL */ msg_t *irq_response; nta_reliable_t *irq_reliable; /**< List of reliable responses */ }; struct nta_reliable_s { nta_reliable_t *rel_next; nta_incoming_t *rel_irq; nta_prack_f *rel_callback; nta_reliable_magic_t *rel_magic; uint32_t rel_rseq; unsigned short rel_status; unsigned rel_pracked:1; unsigned rel_precious:1; msg_t *rel_response; msg_t *rel_unsent; }; typedef struct sipdns_resolver sipdns_resolver_t; struct nta_outgoing_s { hash_value_t orq_hash; /**< Hash value */ nta_agent_t *orq_agent; nta_response_f *orq_callback; nta_outgoing_magic_t *orq_magic; /* Timeout/state queue */ nta_outgoing_t **orq_prev; nta_outgoing_t *orq_next; outgoing_queue_t *orq_queue; /* Retry queue */ nta_outgoing_t **orq_rprev; nta_outgoing_t *orq_rnext; sip_method_t orq_method; char const *orq_method_name; url_t const *orq_url; /**< Original RequestURI */ sip_from_t const *orq_from; sip_to_t const *orq_to; char const *orq_tag; /**< Tag from final response. */ sip_cseq_t const *orq_cseq; sip_call_id_t const *orq_call_id; msg_t *orq_request; msg_t *orq_response; su_time_t orq_sent; /**< When request was sent? */ unsigned orq_delay; /**< RTT estimate */ uint32_t orq_retry; /**< Timer A, E */ uint32_t orq_timeout; /**< Timer B, D, F, K */ unsigned short orq_interval; /**< Next timer A/E */ unsigned short orq_status; unsigned char orq_retries; /**< Number of tries this far */ unsigned orq_default:1; /**< This is default transaction */ unsigned orq_inserted:1; unsigned orq_resolved:1; unsigned orq_via_added:1; unsigned orq_prepared:1; unsigned orq_canceled:1; unsigned orq_terminated:1; unsigned orq_destroyed:1; unsigned orq_completed:1; unsigned orq_delayed:1; unsigned orq_user_tport:1; /**< Application provided tport - don't retry */ unsigned orq_try_tcp_instead:1; unsigned orq_try_udp_instead:1; unsigned orq_reliable:1; /**< Transport is reliable */ unsigned orq_forked:1; /**< Tagged fork */ /* Attributes */ unsigned orq_sips:1; unsigned orq_uas:1; /**< Running this transaction as UAS */ unsigned orq_user_via:1; unsigned orq_stateless:1; unsigned orq_pass_100:1; unsigned orq_sigcomp_new:1; /**< Create compartment if needed */ unsigned orq_sigcomp_zap:1; /**< Reset SigComp after completing */ unsigned orq_must_100rel:1; unsigned orq_timestamp:1; /**< Insert @Timestamp header. */ unsigned orq_100rel:1; /**< Support 100rel */ unsigned:0; /* pad */ #if HAVE_SOFIA_SRESOLV sipdns_resolver_t *orq_resolver; #endif url_t *orq_route; /**< Route URL */ tp_name_t orq_tpn[1]; /**< Where to send request */ tport_t *orq_tport; struct sigcomp_compartment *orq_cc; tagi_t *orq_tags; /**< Tport tag items */ char const *orq_branch; /**< Transaction branch */ char const *orq_via_branch; /**< @Via branch */ int *orq_status2b; /**< Delayed response */ nta_outgoing_t *orq_cancel; /**< Delayed CANCEL transaction */ nta_outgoing_t *orq_forking; /**< Untagged transaction */ nta_outgoing_t *orq_forks; /**< Tagged transactions */ uint32_t orq_rseq; /**< Latest incoming rseq */ int orq_pending; /**< Request is pending in tport */ }; /* ------------------------------------------------------------------------- */ /* Internal tags */ /* Delay sending of request */ #define NTATAG_DELAY_SENDING(x) ntatag_delay_sending, tag_bool_v((x)) #define NTATAG_DELAY_SENDING_REF(x) \ ntatag_delay_sending_ref, tag_bool_vr(&(x)) extern tag_typedef_t ntatag_delay_sending; extern tag_typedef_t ntatag_delay_sending_ref; /* Allow sending incomplete responses */ #define NTATAG_INCOMPLETE(x) ntatag_incomplete, tag_bool_v((x)) #define NTATAG_INCOMPLETE_REF(x) \ ntatag_incomplete_ref, tag_bool_vr(&(x)) extern tag_typedef_t ntatag_incomplete; extern tag_typedef_t ntatag_incomplete_ref; nta_compressor_vtable_t *nta_compressor_vtable = NULL; /* Agent */ static int agent_tag_init(nta_agent_t *self); static int agent_timer_init(nta_agent_t *agent); static void agent_timer(su_root_magic_t *rm, su_timer_t *, nta_agent_t *); static int agent_launch_terminator(nta_agent_t *agent); static void agent_kill_terminator(nta_agent_t *agent); static int agent_set_params(nta_agent_t *agent, tagi_t *tags); static void agent_set_udp_params(nta_agent_t *self, usize_t udp_mtu); static int agent_get_params(nta_agent_t *agent, tagi_t *tags); /* Transport interface */ static sip_via_t const *agent_tport_via(tport_t *tport); static int outgoing_insert_via(nta_outgoing_t *orq, sip_via_t const *); static int nta_tpn_by_via(tp_name_t *tpn, sip_via_t const *v, int *using_rport); static msg_t *nta_msg_create_for_transport(nta_agent_t *agent, int flags, char const data[], usize_t dlen, tport_t const *tport, tp_client_t *via); static int complete_response(msg_t *response, int status, char const *phrase, msg_t *request); static int mreply(nta_agent_t *agent, msg_t *reply, int status, char const *phrase, msg_t *req_msg, tport_t *tport, int incomplete, int sdwn_after, char const *to_tag, tag_type_t tag, tag_value_t value, ...); #define IF_SIGCOMP_TPTAG_COMPARTMENT(cc) TAG_IF(cc && cc != NONE, TPTAG_COMPARTMENT(cc)), #define IF_SIGCOMP_TPTAG_COMPARTMENT_REF(cc) TPTAG_COMPARTMENT_REF(cc), struct sigcomp_compartment; struct sigcomp_compartment * nta_compartment_ref(struct sigcomp_compartment *cc); static struct sigcomp_compartment * agent_compression_compartment(nta_agent_t *sa, tport_t *tp, tp_name_t const *tpn, int new_if_needed); static int agent_accept_compressed(nta_agent_t *sa, msg_t *msg, struct sigcomp_compartment *cc); static int agent_close_compressor(nta_agent_t *sa, struct sigcomp_compartment *cc); static int agent_zap_compressor(nta_agent_t *sa, struct sigcomp_compartment *cc); static char const * stateful_branch(su_home_t *home, nta_agent_t *); static char const * stateless_branch(nta_agent_t *, msg_t *, sip_t const *, tp_name_t const *tp); #define NTA_BRANCH_PRIME SU_U64_C(0xB9591D1C361C6521) #define NTA_TAG_PRIME SU_U64_C(0xB9591D1C361C6521) #ifndef UINT32_MAX #define UINT32_MAX (0xffffffffU) #endif HTABLE_PROTOS_WITH(leg_htable, lht, nta_leg_t, size_t, hash_value_t); static nta_leg_t *leg_find(nta_agent_t const *sa, char const *method_name, url_t const *request_uri, sip_call_id_t const *i, char const *from_tag, char const *to_tag); static nta_leg_t *dst_find(nta_agent_t const *sa, url_t const *u0, char const *method); static void leg_recv(nta_leg_t *, msg_t *, sip_t *, tport_t *); static void leg_free(nta_agent_t *sa, nta_leg_t *leg); #define NTA_HASH(i, cs) ((i)->i_hash + 26839U * (uint32_t)(cs)) HTABLE_PROTOS_WITH(incoming_htable, iht, nta_incoming_t, size_t, hash_value_t); static nta_incoming_t *incoming_create(nta_agent_t *agent, msg_t *request, sip_t *sip, tport_t *tport, char const *tag); static int incoming_callback(nta_leg_t *leg, nta_incoming_t *irq, sip_t *sip); static void incoming_free(nta_incoming_t *irq); su_inline void incoming_cut_off(nta_incoming_t *irq); su_inline void incoming_reclaim(nta_incoming_t *irq); static void incoming_queue_init(incoming_queue_t *, unsigned timeout); static void incoming_queue_adjust(nta_agent_t *sa, incoming_queue_t *queue, unsigned timeout); static nta_incoming_t *incoming_find(nta_agent_t const *agent, sip_t const *sip, sip_via_t const *v, nta_incoming_t **merge, nta_incoming_t **ack, nta_incoming_t **cancel); static int incoming_reply(nta_incoming_t *irq, msg_t *msg, sip_t *sip); su_inline int incoming_recv(nta_incoming_t *irq, msg_t *msg, sip_t *sip, tport_t *tport); su_inline int incoming_ack(nta_incoming_t *irq, msg_t *msg, sip_t *sip, tport_t *tport); su_inline int incoming_cancel(nta_incoming_t *irq, msg_t *msg, sip_t *sip, tport_t *tport); static void request_merge(nta_agent_t *, msg_t *msg, sip_t *sip, tport_t *tport, char const *to_tag); su_inline int incoming_timestamp(nta_incoming_t *, msg_t *, sip_t *); static void _nta_incoming_timer(nta_agent_t *); static nta_reliable_t *reliable_mreply(nta_incoming_t *, nta_prack_f *, nta_reliable_magic_t *, msg_t *, sip_t *); static int reliable_send(nta_incoming_t *, nta_reliable_t *, msg_t *, sip_t *); static int reliable_final(nta_incoming_t *irq, msg_t *msg, sip_t *sip); static msg_t *reliable_response(nta_incoming_t *irq); static nta_reliable_t *reliable_find(nta_agent_t const *, sip_t const *); static int reliable_recv(nta_reliable_t *rel, msg_t *, sip_t *, tport_t *); static void reliable_flush(nta_incoming_t *irq); static void reliable_timeout(nta_incoming_t *irq, int timeout); HTABLE_PROTOS_WITH(outgoing_htable, oht, nta_outgoing_t, size_t, hash_value_t); static nta_outgoing_t *outgoing_create(nta_agent_t *agent, nta_response_f *callback, nta_outgoing_magic_t *magic, url_string_t const *route_url, tp_name_t const *tpn, msg_t *msg, tag_type_t tag, tag_value_t value, ...); static void outgoing_queue_init(outgoing_queue_t *, unsigned timeout); static void outgoing_queue_adjust(nta_agent_t *sa, outgoing_queue_t *queue, unsigned timeout); static void outgoing_free(nta_outgoing_t *orq); su_inline void outgoing_cut_off(nta_outgoing_t *orq); su_inline void outgoing_reclaim(nta_outgoing_t *orq); static nta_outgoing_t *outgoing_find(nta_agent_t const *sa, msg_t const *msg, sip_t const *sip, sip_via_t const *v); static int outgoing_recv(nta_outgoing_t *orq, int status, msg_t *, sip_t *); static void outgoing_default_recv(nta_outgoing_t *, int, msg_t *, sip_t *); static void _nta_outgoing_timer(nta_agent_t *); static int outgoing_recv_reliable(nta_outgoing_t *orq, msg_t *msg, sip_t *sip); /* Internal message passing */ union sm_arg_u { struct outgoing_recv_s { nta_outgoing_t *orq; msg_t *msg; sip_t *sip; int status; } a_outgoing_recv[1]; incoming_queue_t a_incoming_queue[1]; outgoing_queue_t a_outgoing_queue[1]; }; /* Global module data */ /**@var char const NTA_DEBUG[]; * * Environment variable determining the default debug log level. * * The NTA_DEBUG environment variable is used to determine the default * debug logging level. The normal level is 3. * * @sa <sofia-sip/su_debug.h>, #su_log_global, #SOFIA_DEBUG */ #if DOXYGEN_ONLY char const NTA_DEBUG[]; /* dummy declaration for Doxygen */ #endif #ifndef SU_DEBUG #define SU_DEBUG 3 #endif /**Debug log for @b nta module. * * The nta_log is the log object used by @b nta module. The level of * nta_log is set using #NTA_DEBUG environment variable. */ su_log_t nta_log[] = { SU_LOG_INIT("nta", "NTA_DEBUG", SU_DEBUG) }; /* ====================================================================== */ /* 1) Agent */ /** * Create an NTA agent object. * * Create an NTA agent object. The agent * object creates and binds a server socket with address specified in @e url. * If the @e host portion of the @e url is @c "*", the agent listens to all * addresses available on the host. * * When a message is received, the agent object parses it. If the result is * a valid SIP message, the agent object passes the message to the * application by invoking the nta_message_f @e callback function. * * @note * The @e url can be either parsed url (of type url_t ()), or a valid * SIP URL as a string. * * @note * If @e url is @c NULL, the default @e url @c "sip:*" is used. * @par * If @e url is @c NONE (iow, (void*)-1), no server sockets are bound. * @par * If @p transport parameters are specified in @a url, agent uses only * specified transport type. * * @par * If an @p maddr parameter is specified in @e url, agent binds to the * specified address, but uses @e host part of @e url when it generates * @Contact and @Via headers. The @p maddr parameter is also included, * unless it equals to @c INADDR_ANY (@p 0.0.0.0 or @p [::]). * * @param root pointer to a su_root_t used for synchronization * @param contact_url URL that agent uses to bind the server sockets * @param callback pointer to callback function * @param magic pointer to user data * @param tag,value,... tagged arguments * * @TAGS * NTATAG_ALIASES(), * NTATAG_BAD_REQ_MASK(), NTATAG_BAD_RESP_MASK(), NTATAG_BLACKLIST(), * NTATAG_CANCEL_2543(), NTATAG_CANCEL_487(), NTATAG_CLIENT_RPORT(), * NTATAG_DEBUG_DROP_PROB(), NTATAG_DEFAULT_PROXY(), * NTATAG_EXTRA_100(), NTATAG_GRAYLIST(), * NTATAG_MAXSIZE(), NTATAG_MAX_FORWARDS(), NTATAG_MERGE_482(), NTATAG_MCLASS() * NTATAG_PASS_100(), NTATAG_PASS_408(), NTATAG_PRELOAD(), NTATAG_PROGRESS(), * NTATAG_REL100(), * NTATAG_SERVER_RPORT(), * NTATAG_SIPFLAGS(), * NTATAG_SIP_T1X64(), NTATAG_SIP_T1(), NTATAG_SIP_T2(), NTATAG_SIP_T4(), * NTATAG_STATELESS(), * NTATAG_TAG_3261(), NTATAG_TCP_RPORT(), NTATAG_TIMEOUT_408(), * NTATAG_TLS_RPORT(), * NTATAG_TIMER_C(), NTATAG_MAX_PROCEEDING(), * NTATAG_UA(), NTATAG_UDP_MTU(), NTATAG_USER_VIA(), * NTATAG_USE_NAPTR(), NTATAG_USE_SRV() and NTATAG_USE_TIMESTAMP(). * * @note The value from following tags are stored, but they currently do nothing: * NTATAG_SIGCOMP_ALGORITHM(), NTATAG_SIGCOMP_OPTIONS(), NTATAG_SMIME() * * @note It is possible to provide @c (url_string_t*)-1 as @a contact_url. * In that case, no server sockets are bound. * * @retval handle to the agent when successful, * @retval NULL upon an error. * * @sa NUTAG_ */ nta_agent_t *nta_agent_create(su_root_t *root, url_string_t const *contact_url, nta_message_f *callback, nta_agent_magic_t *magic, tag_type_t tag, tag_value_t value, ...) { nta_agent_t *agent; ta_list ta; if (root == NULL) return su_seterrno(EINVAL), NULL; ta_start(ta, tag, value); if ((agent = su_home_new(sizeof(*agent)))) { unsigned timer_c = 0, timer_d = 32000; agent->sa_root = root; agent->sa_callback = callback; agent->sa_magic = magic; agent->sa_flags = MSG_DO_CANONIC; agent->sa_cseq = (su_nanotime(NULL) / 4 / SU_E9) & 0x3fffffff; agent->sa_maxsize = 2 * 1024 * 1024; /* 2 MB */ agent->sa_bad_req_mask = /* * Bit-wise not of these - what is left is suitable for UAs with * 100rel, timer, events, publish */ (unsigned) ~(sip_mask_response | sip_mask_proxy | sip_mask_registrar | sip_mask_pref | sip_mask_privacy); agent->sa_bad_resp_mask = (unsigned) ~(sip_mask_request | sip_mask_proxy | sip_mask_registrar | sip_mask_pref | sip_mask_privacy); agent->sa_t1 = NTA_SIP_T1; agent->sa_t2 = NTA_SIP_T2; agent->sa_t4 = NTA_SIP_T4; agent->sa_t1x64 = 64 * NTA_SIP_T1; agent->sa_timer_c = 185 * 1000; agent->sa_graylist = 600; agent->sa_drop_prob = 0; agent->sa_is_a_uas = 0; agent->sa_progress = 60 * 1000; agent->sa_user_via = 0; agent->sa_extra_100 = 0; agent->sa_pass_100 = 0; agent->sa_timeout_408 = 1; agent->sa_pass_408 = 0; agent->sa_merge_482 = 0; agent->sa_cancel_2543 = 0; agent->sa_cancel_487 = 1; agent->sa_invite_100rel = 0; agent->sa_timestamp = 0; agent->sa_use_naptr = 1; agent->sa_use_srv = 1; agent->sa_auto_comp = 0; agent->sa_server_rport = 1; /* RFC 3261 section 8.1.1.6 */ sip_max_forwards_init(agent->sa_max_forwards); if (getenv("SIPCOMPACT")) agent->sa_flags |= MSG_DO_COMPACT; agent_set_params(agent, ta_args(ta)); if (agent->sa_mclass == NULL) agent->sa_mclass = sip_default_mclass(); agent->sa_in.re_t1 = &agent->sa_in.re_list; incoming_queue_init(agent->sa_in.proceeding, 0); incoming_queue_init(agent->sa_in.preliminary, agent->sa_t1x64); /* P1 */ incoming_queue_init(agent->sa_in.inv_completed, agent->sa_t1x64); /* H */ incoming_queue_init(agent->sa_in.inv_confirmed, agent->sa_t4); /* I */ incoming_queue_init(agent->sa_in.completed, agent->sa_t1x64); /* J */ incoming_queue_init(agent->sa_in.terminated, 0); incoming_queue_init(agent->sa_in.final_failed, 0); agent->sa_out.re_t1 = &agent->sa_out.re_list; if (agent->sa_use_timer_c || !agent->sa_is_a_uas) timer_c = agent->sa_timer_c; if (timer_d < agent->sa_t1x64) timer_d = agent->sa_t1x64; outgoing_queue_init(agent->sa_out.delayed, 0); outgoing_queue_init(agent->sa_out.resolving, 0); outgoing_queue_init(agent->sa_out.trying, agent->sa_t1x64); /* F */ outgoing_queue_init(agent->sa_out.completed, agent->sa_t4); /* K */ outgoing_queue_init(agent->sa_out.terminated, 0); /* Special queues (states) for outgoing INVITE transactions */ outgoing_queue_init(agent->sa_out.inv_calling, agent->sa_t1x64); /* B */ outgoing_queue_init(agent->sa_out.inv_proceeding, timer_c); /* C */ outgoing_queue_init(agent->sa_out.inv_completed, timer_d); /* D */ if (leg_htable_resize(agent->sa_home, agent->sa_dialogs, 0) < 0 || leg_htable_resize(agent->sa_home, agent->sa_defaults, 0) < 0 || outgoing_htable_resize(agent->sa_home, agent->sa_outgoing, 0) < 0 || incoming_htable_resize(agent->sa_home, agent->sa_incoming, 0) < 0) { SU_DEBUG_0(("nta_agent_create: failure with %s\n", "hash tables")); goto deinit; } SU_DEBUG_9(("nta_agent_create: initialized %s\n", "hash tables")); if (contact_url != (url_string_t *)-1 && nta_agent_add_tport(agent, contact_url, ta_tags(ta)) < 0) { SU_DEBUG_7(("nta_agent_create: failure with %s\n", "transport")); goto deinit; } SU_DEBUG_9(("nta_agent_create: initialized %s\n", "transports")); if (agent_tag_init(agent) < 0) { SU_DEBUG_3(("nta_agent_create: failure with %s\n", "random identifiers")); goto deinit; } SU_DEBUG_9(("nta_agent_create: initialized %s\n", "random identifiers")); if (agent_timer_init(agent) < 0) { SU_DEBUG_0(("nta_agent_create: failure with %s\n", "timer")); goto deinit; } SU_DEBUG_9(("nta_agent_create: initialized %s\n", "timer")); if (agent_launch_terminator(agent) == 0) SU_DEBUG_9(("nta_agent_create: initialized %s\n", "threads")); #if HAVE_SOFIA_SRESOLV agent->sa_resolver = sres_resolver_create(root, NULL, ta_tags(ta)); if (!agent->sa_resolver) { SU_DEBUG_0(("nta_agent_create: failure with %s\n", "resolver")); } SU_DEBUG_9(("nta_agent_create: initialized %s\n", "resolver")); #endif ta_end(ta); return agent; deinit: nta_agent_destroy(agent); } ta_end(ta); return NULL; } /** * Destroy an NTA agent object. * * @param agent the NTA agent object to be destroyed. * */ void nta_agent_destroy(nta_agent_t *agent) { if (agent) { size_t i; outgoing_htable_t *oht = agent->sa_outgoing; incoming_htable_t *iht = agent->sa_incoming; /* Currently, this is pretty pointless, as legs don't keep any resources */ leg_htable_t *lht; nta_leg_t *leg; for (i = 0, lht = agent->sa_dialogs; i < lht->lht_size; i++) { if ((leg = lht->lht_table[i])) { SU_DEBUG_3(("nta_agent_destroy: destroying dialog with <" URL_PRINT_FORMAT ">\n", URL_PRINT_ARGS(leg->leg_remote->a_url))); leg_free(agent, leg); } } for (i = 0, lht = agent->sa_defaults; i < lht->lht_size; i++) { if ((leg = lht->lht_table[i])) { SU_DEBUG_3(("%s: destroying leg for <" URL_PRINT_FORMAT ">\n", __func__, URL_PRINT_ARGS(leg->leg_url))); leg_free(agent, leg); } } if (agent->sa_default_leg) leg_free(agent, agent->sa_default_leg); for (i = iht->iht_size; i-- > 0; ) while (iht->iht_table[i]) { nta_incoming_t *irq = iht->iht_table[i]; if (!irq->irq_destroyed) SU_DEBUG_3(("%s: destroying %s server transaction from <" URL_PRINT_FORMAT ">\n", __func__, irq->irq_rq->rq_method_name, URL_PRINT_ARGS(irq->irq_from->a_url))); incoming_free(irq); } for (i = oht->oht_size; i-- > 0;) while (oht->oht_table[i]) { nta_outgoing_t *orq = oht->oht_table[i]; if (!orq->orq_destroyed) SU_DEBUG_3(("%s: destroying %s%s client transaction to <" URL_PRINT_FORMAT ">\n", __func__, (orq->orq_forking || orq->orq_forks) ? "forked " : "forking ", orq->orq_method_name, URL_PRINT_ARGS(orq->orq_to->a_url))); orq->orq_forks = NULL, orq->orq_forking = NULL; outgoing_free(orq); } su_timer_destroy(agent->sa_timer), agent->sa_timer = NULL; # if HAVE_SOFIA_SRESOLV sres_resolver_destroy(agent->sa_resolver), agent->sa_resolver = NULL; # endif tport_destroy(agent->sa_tports), agent->sa_tports = NULL; agent_kill_terminator(agent); su_home_unref(agent->sa_home); } } /** Return agent context. */ nta_agent_magic_t *nta_agent_magic(nta_agent_t const *agent) { return agent ? agent->sa_magic : NULL; } /** Return @Contact header. * * Get a @Contact header, which can be used to reach @a agent. * * @param agent NTA agent object * * User agents can insert the @Contact header in the outgoing REGISTER, * INVITE, and ACK requests and replies to incoming INVITE and OPTIONS * transactions. * * Proxies can use the @Contact header to create appropriate @RecordRoute * headers: * @code * r_r = sip_record_route_create(msg_home(msg), * sip->sip_request->rq_url, * contact->m_url); * @endcode * * @return A sip_contact_t object corresponding to the @a agent. */ sip_contact_t *nta_agent_contact(nta_agent_t const *agent) { return agent ? agent->sa_contact : NULL; } /** Return a list of @Via headers. * * Get @Via headers for all activated transport. * * @param agent NTA agent object * * @return A list of #sip_via_t objects used by the @a agent. */ sip_via_t *nta_agent_via(nta_agent_t const *agent) { return agent ? agent->sa_vias : NULL; } /** Return a list of public (UPnP, STUN) @Via headers. * * Get public @Via headers for all activated transports. * * @param agent NTA agent object * * @return A list of #sip_via_t objects used by the @a agent. */ sip_via_t *nta_agent_public_via(nta_agent_t const *agent) { return agent ? agent->sa_public_vias : NULL; } /** Match a @Via header @a v with @Via headers in @a agent. * */ static sip_via_t *agent_has_via(nta_agent_t const *agent, sip_via_t const *via) { sip_via_t const *v; for (v = agent->sa_public_vias; v; v = v->v_next) { if (!su_casematch(via->v_host, v->v_host)) continue; if (!su_strmatch(via->v_port, v->v_port)) continue; if (!su_casematch(via->v_protocol, v->v_protocol)) continue; return (sip_via_t *)v; } for (v = agent->sa_vias; v; v = v->v_next) { if (!su_casematch(via->v_host, v->v_host)) continue; if (!su_strmatch(via->v_port, v->v_port)) continue; if (!su_casematch(via->v_protocol, v->v_protocol)) continue; return (sip_via_t *)v; } return NULL; } /** Return @UserAgent header. * * Get @UserAgent information with NTA version. * * @param agent NTA agent object (may be NULL) * * @return A string containing the @a agent version. */ char const *nta_agent_version(nta_agent_t const *agent) { return "nta" "/" VERSION; } /** Initialize default tag */ static int agent_tag_init(nta_agent_t *self) { sip_contact_t *m = self->sa_contact; uint32_t hash = su_random(); if (m) { if (m->m_url->url_user) hash = 914715421U * hash + msg_hash_string(m->m_url->url_user); if (m->m_url->url_host) hash = 914715421U * hash + msg_hash_string(m->m_url->url_host); if (m->m_url->url_port) hash = 914715421U * hash + msg_hash_string(m->m_url->url_port); if (m->m_url->url_params) hash = 914715421U * hash + msg_hash_string(m->m_url->url_params); } if (hash == 0) hash = 914715421U; self->sa_branch = NTA_BRANCH_PRIME * (uint64_t)su_nanotime(NULL); self->sa_branch *= hash; self->sa_tags = NTA_TAG_PRIME * self->sa_branch; return 0; } static uint32_t agent_seq(nta_agent_t *agent) { return ++agent->sa_cseq; } /** Initialize agent timer. */ static int agent_timer_init(nta_agent_t *agent) { agent->sa_timer = su_timer_create(su_root_task(agent->sa_root), NTA_SIP_T1 / 8); #if 0 return su_timer_set(agent->sa_timer, agent_timer, agent); #endif return -(agent->sa_timer == NULL); } /** * Agent timer routine. */ static void agent_timer(su_root_magic_t *rm, su_timer_t *timer, nta_agent_t *agent) { su_time_t stamp = su_now(); uint32_t now = su_time_ms(stamp), next, latest; now += now == 0; agent->sa_next = 0; agent->sa_now = stamp; agent->sa_millisec = now; agent->sa_in_timer = 1; _nta_outgoing_timer(agent); _nta_incoming_timer(agent); /* agent->sa_now is used only if sa_millisec != 0 */ agent->sa_millisec = 0; agent->sa_in_timer = 0; /* Calculate next timeout */ next = latest = now + NTA_TIME_MAX + 1; #define NEXT_TIMEOUT(next, p, f, now) \ (void)(p && (int32_t)(p->f - (next)) < 0 && \ ((next) = ((int32_t)(p->f - (now)) > 0 ? p->f : (now)))) NEXT_TIMEOUT(next, agent->sa_out.re_list, orq_retry, now); NEXT_TIMEOUT(next, agent->sa_out.inv_completed->q_head, orq_timeout, now); NEXT_TIMEOUT(next, agent->sa_out.completed->q_head, orq_timeout, now); NEXT_TIMEOUT(next, agent->sa_out.inv_calling->q_head, orq_timeout, now); if (agent->sa_out.inv_proceeding->q_timeout) NEXT_TIMEOUT(next, agent->sa_out.inv_proceeding->q_head, orq_timeout, now); NEXT_TIMEOUT(next, agent->sa_out.trying->q_head, orq_timeout, now); NEXT_TIMEOUT(next, agent->sa_in.preliminary->q_head, irq_timeout, now); NEXT_TIMEOUT(next, agent->sa_in.inv_completed->q_head, irq_timeout, now); NEXT_TIMEOUT(next, agent->sa_in.inv_confirmed->q_head, irq_timeout, now); NEXT_TIMEOUT(next, agent->sa_in.completed->q_head, irq_timeout, now); NEXT_TIMEOUT(next, agent->sa_in.re_list, irq_retry, now); if (agent->sa_next) NEXT_TIMEOUT(next, agent, sa_next, now); #undef NEXT_TIMEOUT if (next == latest) { /* Do not set timer? */ SU_DEBUG_9(("nta: timer not set\n")); assert(!agent->sa_out.completed->q_head); assert(!agent->sa_out.trying->q_head); assert(!agent->sa_out.inv_calling->q_head); assert(!agent->sa_out.re_list); assert(!agent->sa_in.inv_confirmed->q_head); assert(!agent->sa_in.preliminary->q_head); assert(!agent->sa_in.completed->q_head); assert(!agent->sa_in.inv_completed->q_head); assert(!agent->sa_in.re_list); return; } if (next == now) if (++next == 0) ++next; SU_DEBUG_9(("nta: timer %s to %ld ms\n", "set next", (long)(next - now))); agent->sa_next = next; su_timer_set_at(timer, agent_timer, agent, su_time_add(stamp, next - now)); } /** Add uin32_t milliseconds to the time. */ static su_time_t add_milliseconds(su_time_t t0, uint32_t ms) { unsigned long sec = ms / 1000, usec = (ms % 1000) * 1000; t0.tv_usec += usec; t0.tv_sec += sec; if (t0.tv_usec >= 1000000) { t0.tv_sec += 1; t0.tv_usec -= 1000000; } return t0; } /** Calculate nonzero value for timeout. * * Sets or adjusts agent timer when needed. * * @retval 0 if offset is 0 * @retval timeout (millisecond counter) otherwise */ static uint32_t set_timeout(nta_agent_t *agent, uint32_t offset) { su_time_t now; uint32_t next, ms; if (offset == 0) return 0; if (agent->sa_millisec) /* Avoid expensive call to su_now() */ now = agent->sa_now, ms = agent->sa_millisec; else now = su_now(), ms = su_time_ms(now); next = ms + offset; if (next == 0) next = 1; if (agent->sa_in_timer) /* Currently executing timer */ return next; if (agent->sa_next == 0 || (int32_t)(agent->sa_next - next - 5L) > 0) { /* Set timer */ if (agent->sa_next) SU_DEBUG_9(("nta: timer %s to %ld ms\n", "shortened", (long)offset)); else SU_DEBUG_9(("nta: timer %s to %ld ms\n", "set", (long)offset)); su_timer_set_at(agent->sa_timer, agent_timer, agent, add_milliseconds(now, offset)); agent->sa_next = next; } return next; } /** Return current timeval. */ static su_time_t agent_now(nta_agent_t const *agent) { if (agent && agent->sa_millisec != 0) return agent->sa_now; else return su_now(); } /** Launch transaction terminator task */ static int agent_launch_terminator(nta_agent_t *agent) { #ifdef TPTAG_THRPSIZE if (agent->sa_tport_threadpool) { su_home_threadsafe(agent->sa_home); return su_clone_start(agent->sa_root, agent->sa_terminator, NULL, NULL, NULL); } #endif return -1; } /** Kill transaction terminator task */ static void agent_kill_terminator(nta_agent_t *agent) { su_clone_wait(agent->sa_root, agent->sa_terminator); } /**Set NTA Parameters. * * The nta_agent_set_params() function sets the stack parameters. The * parameters determine the way NTA handles the retransmissions, how long * NTA keeps transactions alive, does NTA apply proxy or user-agent logic to * INVITE transactions, or how the @Via headers are generated. * * @note * Setting the parameters NTATAG_MAXSIZE(), NTATAG_UDP_MTU(), NTATAG_MAX_PROCEEDING(), * NTATAG_SIP_T1X64(), NTATAG_SIP_T1(), NTATAG_SIP_T2(), NTATAG_SIP_T4() to * 0 selects the default value. * * @TAGS * NTATAG_ALIASES(), * NTATAG_BAD_REQ_MASK(), NTATAG_BAD_RESP_MASK(), NTATAG_BLACKLIST(), * NTATAG_CANCEL_2543(), NTATAG_CANCEL_487(), NTATAG_CLIENT_RPORT(), * NTATAG_DEBUG_DROP_PROB(), NTATAG_DEFAULT_PROXY(), * NTATAG_EXTRA_100(), NTATAG_GRAYLIST(), * NTATAG_MAXSIZE(), NTATAG_MAX_FORWARDS(), NTATAG_MERGE_482(), NTATAG_MCLASS() * NTATAG_PASS_100(), NTATAG_PASS_408(), NTATAG_PRELOAD(), NTATAG_PROGRESS(), * NTATAG_REL100(), * NTATAG_SERVER_RPORT(), * NTATAG_SIPFLAGS(), * NTATAG_SIP_T1X64(), NTATAG_SIP_T1(), NTATAG_SIP_T2(), NTATAG_SIP_T4(), * NTATAG_STATELESS(), * NTATAG_TAG_3261(), NTATAG_TCP_RPORT(), NTATAG_TIMEOUT_408(), * NTATAG_TLS_RPORT(), * NTATAG_TIMER_C(), NTATAG_MAX_PROCEEDING(), * NTATAG_UA(), NTATAG_UDP_MTU(), NTATAG_USER_VIA(), * NTATAG_USE_NAPTR(), NTATAG_USE_SRV() and NTATAG_USE_TIMESTAMP(). * * @note The value from following tags are stored, but they currently do nothing: * NTATAG_SIGCOMP_ALGORITHM(), NTATAG_SIGCOMP_OPTIONS(), NTATAG_SMIME() */ int nta_agent_set_params(nta_agent_t *agent, tag_type_t tag, tag_value_t value, ...) { int retval; if (agent) { ta_list ta; ta_start(ta, tag, value); retval = agent_set_params(agent, ta_args(ta)); ta_end(ta); } else { su_seterrno(EINVAL); retval = -1; } return retval; } /** Internal function for setting tags */ static int agent_set_params(nta_agent_t *agent, tagi_t *tags) { int n, nC, m; unsigned bad_req_mask = agent->sa_bad_req_mask; unsigned bad_resp_mask = agent->sa_bad_resp_mask; usize_t maxsize = agent->sa_maxsize; usize_t max_proceeding = agent->sa_max_proceeding; unsigned max_forwards = agent->sa_max_forwards->mf_count; unsigned udp_mtu = agent->sa_udp_mtu; unsigned sip_t1 = agent->sa_t1; unsigned sip_t2 = agent->sa_t2; unsigned sip_t4 = agent->sa_t4; unsigned sip_t1x64 = agent->sa_t1x64; unsigned timer_c = agent->sa_timer_c; unsigned timer_d = 32000; unsigned graylist = agent->sa_graylist; unsigned blacklist = agent->sa_blacklist; int ua = agent->sa_is_a_uas; unsigned progress = agent->sa_progress; int stateless = agent->sa_is_stateless; unsigned drop_prob = agent->sa_drop_prob; int user_via = agent->sa_user_via; int extra_100 = agent->sa_extra_100; int pass_100 = agent->sa_pass_100; int timeout_408 = agent->sa_timeout_408; int pass_408 = agent->sa_pass_408; int merge_482 = agent->sa_merge_482; int cancel_2543 = agent->sa_cancel_2543; int cancel_487 = agent->sa_cancel_487; int invite_100rel = agent->sa_invite_100rel; int use_timestamp = agent->sa_timestamp; int use_naptr = agent->sa_use_naptr; int use_srv = agent->sa_use_srv; void *smime = agent->sa_smime; uint32_t flags = agent->sa_flags; int rport = agent->sa_rport; int server_rport = agent->sa_server_rport; int tcp_rport = agent->sa_tcp_rport; int tls_rport = agent->sa_tls_rport; unsigned preload = agent->sa_preload; unsigned threadpool = agent->sa_tport_threadpool; char const *sigcomp = agent->sa_sigcomp_options; char const *algorithm = NONE; msg_mclass_t const *mclass = NONE; sip_contact_t const *aliases = NONE; url_string_t const *proxy = NONE; tport_t *tport; su_home_t *home = agent->sa_home; n = tl_gets(tags, NTATAG_ALIASES_REF(aliases), NTATAG_BAD_REQ_MASK_REF(bad_req_mask), NTATAG_BAD_RESP_MASK_REF(bad_resp_mask), NTATAG_BLACKLIST_REF(blacklist), NTATAG_CANCEL_2543_REF(cancel_2543), NTATAG_CANCEL_487_REF(cancel_487), NTATAG_DEBUG_DROP_PROB_REF(drop_prob), NTATAG_DEFAULT_PROXY_REF(proxy), NTATAG_EXTRA_100_REF(extra_100), NTATAG_GRAYLIST_REF(graylist), NTATAG_MAXSIZE_REF(maxsize), NTATAG_MAX_PROCEEDING_REF(max_proceeding), NTATAG_MAX_FORWARDS_REF(max_forwards), NTATAG_MCLASS_REF(mclass), NTATAG_MERGE_482_REF(merge_482), NTATAG_PASS_100_REF(pass_100), NTATAG_PASS_408_REF(pass_408), NTATAG_PRELOAD_REF(preload), NTATAG_PROGRESS_REF(progress), NTATAG_REL100_REF(invite_100rel), NTATAG_RPORT_REF(rport), NTATAG_SERVER_RPORT_REF(server_rport), NTATAG_SIGCOMP_ALGORITHM_REF(algorithm), NTATAG_SIGCOMP_OPTIONS_REF(sigcomp), NTATAG_SIPFLAGS_REF(flags), NTATAG_SIP_T1X64_REF(sip_t1x64), NTATAG_SIP_T1_REF(sip_t1), NTATAG_SIP_T2_REF(sip_t2), NTATAG_SIP_T4_REF(sip_t4), #if HAVE_SOFIA_SMIME NTATAG_SMIME_REF(smime), #endif NTATAG_STATELESS_REF(stateless), NTATAG_TCP_RPORT_REF(tcp_rport), NTATAG_TLS_RPORT_REF(tls_rport), NTATAG_TIMEOUT_408_REF(timeout_408), NTATAG_UA_REF(ua), NTATAG_UDP_MTU_REF(udp_mtu), NTATAG_USER_VIA_REF(user_via), NTATAG_USE_NAPTR_REF(use_naptr), NTATAG_USE_SRV_REF(use_srv), NTATAG_USE_TIMESTAMP_REF(use_timestamp), #ifdef TPTAG_THRPSIZE /* If threadpool is enabled, start a separate "reaper thread" */ TPTAG_THRPSIZE_REF(threadpool), #endif TAG_END()); nC = tl_gets(tags, NTATAG_TIMER_C_REF(timer_c), TAG_END()); n += nC; if (mclass != NONE) agent->sa_mclass = mclass ? mclass : sip_default_mclass(); m = 0; for (tport = agent->sa_tports; tport; tport = tport_next(tport)) { int m0 = tport_set_params(tport, TAG_NEXT(tags)); if (m0 < 0) return m0; if (m0 > m) m = m0; } n += m; if (aliases != NONE) { sip_contact_t const *m, *m_next; m = agent->sa_aliases; agent->sa_aliases = sip_contact_dup(home, aliases); for (; m; m = m_next) { /* Free old aliases */ m_next = m->m_next; su_free(home, (void *)m); } } if (proxy != NONE) { url_t *dp = url_hdup(home, proxy->us_url); url_sanitize(dp); if (dp == NULL || dp->url_type == url_sip || dp->url_type == url_sips) { if (agent->sa_default_proxy) su_free(home, agent->sa_default_proxy); agent->sa_default_proxy = dp; } else n = -1; } if (algorithm != NONE) agent->sa_algorithm = su_strdup(home, algorithm); if (!su_strmatch(sigcomp, agent->sa_sigcomp_options)) { msg_param_t const *l = NULL; char *s = su_strdup(home, sigcomp); char *s1 = su_strdup(home, s), *s2 = s1; if (s && s2 && msg_avlist_d(home, &s2, &l) == 0 && *s2 == '\0') { su_free(home, (void *)agent->sa_sigcomp_options); su_free(home, (void *)agent->sa_sigcomp_option_list); agent->sa_sigcomp_options = s; agent->sa_sigcomp_option_free = s1; agent->sa_sigcomp_option_list = l; } else { su_free(home, s); su_free(home, s1); su_free(home, (void *)l); n = -1; } } if (maxsize == 0) maxsize = 2 * 1024 * 1024; if (maxsize > UINT32_MAX) maxsize = UINT32_MAX; agent->sa_maxsize = maxsize; if (max_proceeding == 0) max_proceeding = USIZE_MAX; agent->sa_max_proceeding = max_proceeding; if (max_forwards == 0) max_forwards = 70; /* Default value */ agent->sa_max_forwards->mf_count = max_forwards; if (udp_mtu == 0) udp_mtu = 1300; if (udp_mtu > 65535) udp_mtu = 65535; if (agent->sa_udp_mtu != udp_mtu) { agent->sa_udp_mtu = udp_mtu; agent_set_udp_params(agent, udp_mtu); } if (sip_t1 == 0) sip_t1 = NTA_SIP_T1; if (sip_t1 > NTA_TIME_MAX) sip_t1 = NTA_TIME_MAX; agent->sa_t1 = sip_t1; if (sip_t2 == 0) sip_t2 = NTA_SIP_T2; if (sip_t2 > NTA_TIME_MAX) sip_t2 = NTA_TIME_MAX; agent->sa_t2 = sip_t2; if (sip_t4 == 0) sip_t4 = NTA_SIP_T4; if (sip_t4 > NTA_TIME_MAX) sip_t4 = NTA_TIME_MAX; if (agent->sa_t4 != sip_t4) { incoming_queue_adjust(agent, agent->sa_in.inv_confirmed, sip_t4); outgoing_queue_adjust(agent, agent->sa_out.completed, sip_t4); } agent->sa_t4 = sip_t4; if (sip_t1x64 == 0) sip_t1x64 = NTA_SIP_T1 * 64; if (sip_t1x64 > NTA_TIME_MAX) sip_t1x64 = NTA_TIME_MAX; if (agent->sa_t1x64 != sip_t1x64) { incoming_queue_adjust(agent, agent->sa_in.preliminary, sip_t1x64); incoming_queue_adjust(agent, agent->sa_in.completed, sip_t1x64); incoming_queue_adjust(agent, agent->sa_in.inv_completed, sip_t1x64); outgoing_queue_adjust(agent, agent->sa_out.trying, sip_t1x64); outgoing_queue_adjust(agent, agent->sa_out.inv_calling, sip_t1x64); } agent->sa_t1x64 = sip_t1x64; if (nC == 1) { agent->sa_use_timer_c = 1; if (timer_c == 0) timer_c = 185 * 1000; agent->sa_timer_c = timer_c; outgoing_queue_adjust(agent, agent->sa_out.inv_proceeding, timer_c); } if (timer_d < sip_t1x64) timer_d = sip_t1x64; outgoing_queue_adjust(agent, agent->sa_out.inv_completed, timer_d); if (graylist > 24 * 60 * 60) graylist = 24 * 60 * 60; agent->sa_graylist = graylist; if (blacklist > 24 * 60 * 60) blacklist = 24 * 60 * 60; agent->sa_blacklist = blacklist; if (progress == 0) progress = 60 * 1000; agent->sa_progress = progress; if (server_rport > 3) server_rport = 1; else if (server_rport < 0) server_rport = 1; agent->sa_server_rport = server_rport; agent->sa_bad_req_mask = bad_req_mask; agent->sa_bad_resp_mask = bad_resp_mask; agent->sa_is_a_uas = ua != 0; agent->sa_is_stateless = stateless != 0; agent->sa_drop_prob = drop_prob < 1000 ? drop_prob : 1000; agent->sa_user_via = user_via != 0; agent->sa_extra_100 = extra_100 != 0; agent->sa_pass_100 = pass_100 != 0; agent->sa_timeout_408 = timeout_408 != 0; agent->sa_pass_408 = pass_408 != 0; agent->sa_merge_482 = merge_482 != 0; agent->sa_cancel_2543 = cancel_2543 != 0; agent->sa_cancel_487 = cancel_487 != 0; agent->sa_invite_100rel = invite_100rel != 0; agent->sa_timestamp = use_timestamp != 0; agent->sa_use_naptr = use_naptr != 0; agent->sa_use_srv = use_srv != 0; agent->sa_smime = smime; agent->sa_flags = flags & MSG_FLG_USERMASK; agent->sa_rport = rport != 0; agent->sa_tcp_rport = tcp_rport != 0; agent->sa_tls_rport = tls_rport != 0; agent->sa_preload = preload; agent->sa_tport_threadpool = threadpool; return n; } static void agent_set_udp_params(nta_agent_t *self, usize_t udp_mtu) { tport_t *tp; /* Set via fields for the tports */ for (tp = tport_primaries(self->sa_tports); tp; tp = tport_next(tp)) { if (tport_is_udp(tp)) tport_set_params(tp, TPTAG_TIMEOUT(2 * self->sa_t1x64), TPTAG_MTU(udp_mtu), TAG_END()); } } /**Get NTA Parameters. * * The nta_agent_get_params() function retrieves the stack parameters. The * parameters determine the way NTA handles the retransmissions, how long * NTA keeps transactions alive, does NTA apply proxy or user-agent logic to * INVITE transactions, or how the @Via headers are generated. * * @TAGS * NTATAG_ALIASES_REF(), NTATAG_BLACKLIST_REF(), * NTATAG_CANCEL_2543_REF(), NTATAG_CANCEL_487_REF(), * NTATAG_CLIENT_RPORT_REF(), NTATAG_CONTACT_REF(), * NTATAG_DEBUG_DROP_PROB_REF(), NTATAG_DEFAULT_PROXY_REF(), * NTATAG_EXTRA_100_REF(), NTATAG_GRAYLIST_REF(), * NTATAG_MAXSIZE_REF(), NTATAG_MAX_FORWARDS_REF(), NTATAG_MCLASS_REF(), * NTATAG_MERGE_482_REF(), NTATAG_MAX_PROCEEDING_REF(), * NTATAG_PASS_100_REF(), NTATAG_PASS_408_REF(), NTATAG_PRELOAD_REF(), * NTATAG_PROGRESS_REF(), * NTATAG_REL100_REF(), * NTATAG_SERVER_RPORT_REF(), * NTATAG_SIGCOMP_ALGORITHM_REF(), NTATAG_SIGCOMP_OPTIONS_REF(), * NTATAG_SIPFLAGS_REF(), * NTATAG_SIP_T1_REF(), NTATAG_SIP_T1X64_REF(), NTATAG_SIP_T2_REF(), * NTATAG_SIP_T4_REF(), NTATAG_SMIME_REF(), NTATAG_STATELESS_REF(), * NTATAG_TAG_3261_REF(), NTATAG_TIMEOUT_408_REF(), NTATAG_TIMER_C_REF(), * NTATAG_UA_REF(), NTATAG_UDP_MTU_REF(), NTATAG_USER_VIA_REF(), * NTATAG_USE_NAPTR_REF(), NTATAG_USE_SRV_REF(), * and NTATAG_USE_TIMESTAMP_REF(). * */ int nta_agent_get_params(nta_agent_t *agent, tag_type_t tag, tag_value_t value, ...) { int n; ta_list ta; if (agent) { ta_start(ta, tag, value); n = agent_get_params(agent, ta_args(ta)); ta_end(ta); return n; } su_seterrno(EINVAL); return -1; } /** Get NTA parameters */ static int agent_get_params(nta_agent_t *agent, tagi_t *tags) { return tl_tgets(tags, NTATAG_ALIASES(agent->sa_aliases), NTATAG_BLACKLIST(agent->sa_blacklist), NTATAG_CANCEL_2543(agent->sa_cancel_2543), NTATAG_CANCEL_487(agent->sa_cancel_487), NTATAG_CLIENT_RPORT(agent->sa_rport), NTATAG_CONTACT(agent->sa_contact), NTATAG_DEBUG_DROP_PROB(agent->sa_drop_prob), NTATAG_DEFAULT_PROXY(agent->sa_default_proxy), NTATAG_EXTRA_100(agent->sa_extra_100), NTATAG_GRAYLIST(agent->sa_graylist), NTATAG_MAXSIZE(agent->sa_maxsize), NTATAG_MAX_PROCEEDING(agent->sa_max_proceeding), NTATAG_MAX_FORWARDS(agent->sa_max_forwards->mf_count), NTATAG_MCLASS(agent->sa_mclass), NTATAG_MERGE_482(agent->sa_merge_482), NTATAG_PASS_100(agent->sa_pass_100), NTATAG_PASS_408(agent->sa_pass_408), NTATAG_PRELOAD(agent->sa_preload), NTATAG_PROGRESS(agent->sa_progress), NTATAG_REL100(agent->sa_invite_100rel), NTATAG_SERVER_RPORT((int)(agent->sa_server_rport)), NTATAG_SIGCOMP_ALGORITHM(agent->sa_algorithm), NTATAG_SIGCOMP_OPTIONS(agent->sa_sigcomp_options ? agent->sa_sigcomp_options : "sip"), NTATAG_SIPFLAGS(agent->sa_flags), NTATAG_SIP_T1(agent->sa_t1), NTATAG_SIP_T1X64(agent->sa_t1x64), NTATAG_SIP_T2(agent->sa_t2), NTATAG_SIP_T4(agent->sa_t4), #if HAVE_SOFIA_SMIME NTATAG_SMIME(agent->sa_smime), #else NTATAG_SMIME(NULL), #endif NTATAG_STATELESS(agent->sa_is_stateless), NTATAG_TAG_3261(1), NTATAG_TIMEOUT_408(agent->sa_timeout_408), NTATAG_TIMER_C(agent->sa_timer_c), NTATAG_UA(agent->sa_is_a_uas), NTATAG_UDP_MTU(agent->sa_udp_mtu), NTATAG_USER_VIA(agent->sa_user_via), NTATAG_USE_NAPTR(agent->sa_use_naptr), NTATAG_USE_SRV(agent->sa_use_srv), NTATAG_USE_TIMESTAMP(agent->sa_timestamp), TAG_END()); } /**Get NTA statistics. * * The nta_agent_get_stats() function retrieves the stack statistics. * * @TAGS * NTATAG_S_ACKED_TR_REF(), * NTATAG_S_BAD_MESSAGE_REF(), * NTATAG_S_BAD_REQUEST_REF(), * NTATAG_S_BAD_RESPONSE_REF(), * NTATAG_S_CANCELED_TR_REF(), * NTATAG_S_CLIENT_TR_REF(), * NTATAG_S_DIALOG_TR_REF(), * NTATAG_S_DROP_REQUEST_REF(), * NTATAG_S_DROP_RESPONSE_REF(), * NTATAG_S_IRQ_HASH_REF(), * NTATAG_S_IRQ_HASH_USED_REF(), * NTATAG_S_LEG_HASH_REF(), * NTATAG_S_LEG_HASH_USED_REF(), * NTATAG_S_MERGED_REQUEST_REF(), * NTATAG_S_ORQ_HASH_REF(), * NTATAG_S_ORQ_HASH_USED_REF(), * NTATAG_S_RECV_MSG_REF(), * NTATAG_S_RECV_REQUEST_REF(), * NTATAG_S_RECV_RESPONSE_REF(), * NTATAG_S_RECV_RETRY_REF(), * NTATAG_S_RETRY_REQUEST_REF(), * NTATAG_S_RETRY_RESPONSE_REF(), * NTATAG_S_SENT_MSG_REF(), * NTATAG_S_SENT_REQUEST_REF(), * NTATAG_S_SENT_RESPONSE_REF(), * NTATAG_S_SERVER_TR_REF(), * NTATAG_S_TOUT_REQUEST_REF(), * NTATAG_S_TOUT_RESPONSE_REF(), * NTATAG_S_TRLESS_200_REF(), * NTATAG_S_TRLESS_REQUEST_REF(), * NTATAG_S_TRLESS_RESPONSE_REF(), and * NTATAG_S_TRLESS_TO_TR_REF(), */ int nta_agent_get_stats(nta_agent_t *agent, tag_type_t tag, tag_value_t value, ...) { int n; ta_list ta; if (!agent) return su_seterrno(EINVAL); ta_start(ta, tag, value); n = tl_tgets(ta_args(ta), NTATAG_S_IRQ_HASH(agent->sa_incoming->iht_size), NTATAG_S_ORQ_HASH(agent->sa_outgoing->oht_size), NTATAG_S_LEG_HASH(agent->sa_dialogs->lht_size), NTATAG_S_IRQ_HASH_USED(agent->sa_incoming->iht_used), NTATAG_S_ORQ_HASH_USED(agent->sa_outgoing->oht_used), NTATAG_S_LEG_HASH_USED(agent->sa_dialogs->lht_used), NTATAG_S_RECV_MSG(agent->sa_stats->as_recv_msg), NTATAG_S_RECV_REQUEST(agent->sa_stats->as_recv_request), NTATAG_S_RECV_RESPONSE(agent->sa_stats->as_recv_response), NTATAG_S_BAD_MESSAGE(agent->sa_stats->as_bad_message), NTATAG_S_BAD_REQUEST(agent->sa_stats->as_bad_request), NTATAG_S_BAD_RESPONSE(agent->sa_stats->as_bad_response), NTATAG_S_DROP_REQUEST(agent->sa_stats->as_drop_request), NTATAG_S_DROP_RESPONSE(agent->sa_stats->as_drop_response), NTATAG_S_CLIENT_TR(agent->sa_stats->as_client_tr), NTATAG_S_SERVER_TR(agent->sa_stats->as_server_tr), NTATAG_S_DIALOG_TR(agent->sa_stats->as_dialog_tr), NTATAG_S_ACKED_TR(agent->sa_stats->as_acked_tr), NTATAG_S_CANCELED_TR(agent->sa_stats->as_canceled_tr), NTATAG_S_TRLESS_REQUEST(agent->sa_stats->as_trless_request), NTATAG_S_TRLESS_TO_TR(agent->sa_stats->as_trless_to_tr), NTATAG_S_TRLESS_RESPONSE(agent->sa_stats->as_trless_response), NTATAG_S_TRLESS_200(agent->sa_stats->as_trless_200), NTATAG_S_MERGED_REQUEST(agent->sa_stats->as_merged_request), NTATAG_S_SENT_MSG(agent->sa_stats->as_sent_msg), NTATAG_S_SENT_REQUEST(agent->sa_stats->as_sent_request), NTATAG_S_SENT_RESPONSE(agent->sa_stats->as_sent_response), NTATAG_S_RETRY_REQUEST(agent->sa_stats->as_retry_request), NTATAG_S_RETRY_RESPONSE(agent->sa_stats->as_retry_response), NTATAG_S_RECV_RETRY(agent->sa_stats->as_recv_retry), NTATAG_S_TOUT_REQUEST(agent->sa_stats->as_tout_request), NTATAG_S_TOUT_RESPONSE(agent->sa_stats->as_tout_response), TAG_END()); ta_end(ta); return n; } /**Calculate a new unique tag. * * This function generates a series of 2**64 unique tags for @From or @To * headers. The start of the tag series is derived from the NTP time the NTA * agent was initialized. * */ char const *nta_agent_newtag(su_home_t *home, char const *fmt, nta_agent_t *sa) { char tag[(8 * 8 + 4)/ 5 + 1]; if (sa == NULL) return su_seterrno(EINVAL), NULL; /* XXX - use a cryptographically safe func here? */ sa->sa_tags += NTA_TAG_PRIME; msg_random_token(tag, sizeof(tag) - 1, &sa->sa_tags, sizeof(sa->sa_tags)); if (fmt && fmt[0]) return su_sprintf(home, fmt, tag); else return su_strdup(home, tag); } /** * Calculate branch value. */ static char const *stateful_branch(su_home_t *home, nta_agent_t *sa) { char branch[(8 * 8 + 4)/ 5 + 1]; /* XXX - use a cryptographically safe func here? */ sa->sa_branch += NTA_BRANCH_PRIME; msg_random_token(branch, sizeof(branch) - 1, &sa->sa_branch, sizeof(sa->sa_branch)); return su_sprintf(home, "branch=z9hG4bK%s", branch); } #include <sofia-sip/su_md5.h> /** * Calculate branch value for stateless operation. * * XXX - should include HMAC of previous @Via line. */ static char const *stateless_branch(nta_agent_t *sa, msg_t *msg, sip_t const *sip, tp_name_t const *tpn) { su_md5_t md5[1]; uint8_t digest[SU_MD5_DIGEST_SIZE]; char branch[(SU_MD5_DIGEST_SIZE * 8 + 4)/ 5 + 1]; sip_route_t const *r; assert(sip->sip_request); if (!sip->sip_via) return stateful_branch(msg_home(msg), sa); su_md5_init(md5); su_md5_str0update(md5, tpn->tpn_host); su_md5_str0update(md5, tpn->tpn_port); url_update(md5, sip->sip_request->rq_url); if (sip->sip_call_id) { su_md5_str0update(md5, sip->sip_call_id->i_id); } if (sip->sip_from) { url_update(md5, sip->sip_from->a_url); su_md5_stri0update(md5, sip->sip_from->a_tag); } if (sip->sip_to) { url_update(md5, sip->sip_to->a_url); /* XXX - some broken implementations include To tag in CANCEL */ /* su_md5_str0update(md5, sip->sip_to->a_tag); */ } if (sip->sip_cseq) { uint32_t cseq = htonl(sip->sip_cseq->cs_seq); su_md5_update(md5, &cseq, sizeof(cseq)); } for (r = sip->sip_route; r; r = r->r_next) url_update(md5, r->r_url); su_md5_digest(md5, digest); msg_random_token(branch, sizeof(branch) - 1, digest, sizeof(digest)); return su_sprintf(msg_home(msg), "branch=z9hG4bK.%s", branch); } /* ====================================================================== */ /* 2) Transport interface */ /* Local prototypes */ static int agent_create_master_transport(nta_agent_t *self, tagi_t *tags); static int agent_init_via(nta_agent_t *self, tport_t *primaries, int use_maddr); static int agent_init_contact(nta_agent_t *self); static void agent_recv_message(nta_agent_t *agent, tport_t *tport, msg_t *msg, sip_via_t *tport_via, su_time_t now); static void agent_tp_error(nta_agent_t *agent, tport_t *tport, int errcode, char const *remote); static void agent_update_tport(nta_agent_t *agent, tport_t *); /**For each transport, we have name used by tport module, SRV prefixes used * for resolving, and NAPTR service/conversion. */ static struct sipdns_tport { char name[6]; /**< Named used by tport module */ char port[6]; /**< Default port number */ char prefix[14]; /**< Prefix for SRV domains */ char service[10]; /**< NAPTR service */ } #define SIPDNS_TRANSPORTS (4) const sipdns_tports[SIPDNS_TRANSPORTS] = { { "udp", "5060", "_sip._udp.", "SIP+D2U" }, { "tcp", "5060", "_sip._tcp.", "SIP+D2T" }, { "sctp", "5060", "_sip._sctp.", "SIP+D2S" }, { "tls", "5061", "_sips._tcp.", "SIPS+D2T" }, }; static char const * const tports_sip[] = { "udp", "tcp", "sctp", NULL }; static char const * const tports_sips[] = { "tls", NULL }; static tport_stack_class_t nta_agent_class[1] = {{ sizeof(nta_agent_class), agent_recv_message, agent_tp_error, nta_msg_create_for_transport, agent_update_tport, }}; /** Add a transport to the agent. * * Creates a new transport and binds it * to the port specified by the @a uri. The @a uri must have sip: or sips: * scheme or be a wildcard uri ("*"). The @a uri syntax allowed is as * follows: * * @code url <scheme>:<host>[:<port>]<url-params> @endcode * where <url-params> may be * @code * ;transport=<xxx> * ;maddr=<actual addr> * ;comp=sigcomp * @endcode * * The scheme part determines which transports are used. "sip" implies UDP * and TCP, "sips" TLS over TCP. In the future, more transports can be * supported, for instance, "sip" can use SCTP or DCCP, "sips" DTLS or TLS * over SCTP. * * The "host" part determines what address/domain name is used in @Contact. * An "*" in "host" part is shorthand for any local IP address. 0.0.0.0 * means that the only the IPv4 addresses are used. [::] means that only * the IPv6 addresses are used. If a domain name or a specific IP address * is given as "host" part, an additional "maddr" parameter can be used to * control which addresses are used by the stack when binding listen * sockets for incoming requests. * * The "port" determines what port is used in contact, and to which port the * stack binds in order to listen for incoming requests. Empty or missing * port means that default port should be used (5060 for sip, 5061 for * sips). An "*" in "port" part means any port, i.e., the stack binds to an * ephemeral port. * * The "transport" parameter determines the transport protocol that is used * and how they are preferred. If no protocol is specified, both UDP and TCP * are used for SIP URL and TLS for SIPS URL. The preference can be * indicated with a comma-separated list of transports, for instance, * parameter @code transport=tcp,udp @endcode indicates that TCP is * preferred to UDP. * * The "maddr" parameter determines to which address the stack binds in * order to listen for incoming requests. An "*" in "maddr" parameter is * shorthand for any local IP address. 0.0.0.0 means that only IPv4 sockets * are created. [::] means that only IPv6 sockets are created. * * The "comp" parameter determines the supported compression protocol. * Currently only sigcomp is supported (with suitable library). * * @par Examples: * @code sip:172.21.40.24;maddr=* @endcode \n * @code sip:172.21.40.24:50600;transport=TCP,UDP;comp=sigcomp @endcode \n * @code sips:* @endcode * * @return * On success, zero is returned. On error, -1 is returned, and @a errno is * set appropriately. */ int nta_agent_add_tport(nta_agent_t *self, url_string_t const *uri, tag_type_t tag, tag_value_t value, ...) { url_t *url; char tp[32]; char maddr[256]; char comp[32]; tp_name_t tpn[1] = {{ NULL }}; char const * const * tports = tports_sip; int error; ta_list ta; if (self == NULL) { su_seterrno(EINVAL); return -1; } if (uri == NULL) uri = (url_string_t *)"sip:*"; else if (url_string_p(uri) ? strcmp(uri->us_str, "*") == 0 : uri->us_url->url_type == url_any) { uri = (url_string_t *)"sip:*:*"; } if (!(url = url_hdup(self->sa_home, uri->us_url)) || (url->url_type != url_sip && url->url_type != url_sips)) { if (url_string_p(uri)) SU_DEBUG_1(("nta: %s: invalid bind URL\n", uri->us_str)); else SU_DEBUG_1(("nta: invalid bind URL\n")); su_seterrno(EINVAL); return -1; } tpn->tpn_canon = url->url_host; tpn->tpn_host = url->url_host; tpn->tpn_port = url_port(url); if (url->url_type == url_sip) { tpn->tpn_proto = "*"; tports = tports_sip; if (!tpn->tpn_port || !tpn->tpn_port[0]) tpn->tpn_port = SIP_DEFAULT_SERV; } else { assert(url->url_type == url_sips); tpn->tpn_proto = "*"; tports = tports_sips; if (!tpn->tpn_port || !tpn->tpn_port[0]) tpn->tpn_port = SIPS_DEFAULT_SERV; } if (url->url_params) { if (url_param(url->url_params, "transport", tp, sizeof(tp)) > 0) { if (strchr(tp, ',')) { int i; char *t, *tps[9]; /* Split tp into transports */ for (i = 0, t = tp; t && i < 8; i++) { tps[i] = t; if ((t = strchr(t, ','))) *t++ = '\0'; } tps[i] = NULL; tports = (char const * const *)tps; } else { tpn->tpn_proto = tp; } } if (url_param(url->url_params, "maddr", maddr, sizeof(maddr)) > 0) tpn->tpn_host = maddr; if (url_param(url->url_params, "comp", comp, sizeof(comp)) > 0) tpn->tpn_comp = comp; if (tpn->tpn_comp && (nta_compressor_vtable == NULL || !su_casematch(tpn->tpn_comp, nta_compressor_vtable->ncv_name))) { SU_DEBUG_1(("nta(%p): comp=%s not supported for " URL_PRINT_FORMAT "\n", (void *)self, tpn->tpn_comp, URL_PRINT_ARGS(url))); } } ta_start(ta, tag, value); if (self->sa_tports == NULL) { if (agent_create_master_transport(self, ta_args(ta)) < 0) { error = su_errno(); SU_DEBUG_1(("nta: cannot create master transport: %s\n", su_strerror(error))); goto error; } } if (tport_tbind(self->sa_tports, tpn, tports, ta_tags(ta)) < 0) { error = su_errno(); SU_DEBUG_1(("nta: bind(%s:%s;transport=%s%s%s%s%s): %s\n", tpn->tpn_canon, tpn->tpn_port, tpn->tpn_proto, tpn->tpn_canon != tpn->tpn_host ? ";maddr=" : "", tpn->tpn_canon != tpn->tpn_host ? tpn->tpn_host : "", tpn->tpn_comp ? ";comp=" : "", tpn->tpn_comp ? tpn->tpn_comp : "", su_strerror(error))); goto error; } else SU_DEBUG_5(("nta: bound to (%s:%s;transport=%s%s%s%s%s)\n", tpn->tpn_canon, tpn->tpn_port, tpn->tpn_proto, tpn->tpn_canon != tpn->tpn_host ? ";maddr=" : "", tpn->tpn_canon != tpn->tpn_host ? tpn->tpn_host : "", tpn->tpn_comp ? ";comp=" : "", tpn->tpn_comp ? tpn->tpn_comp : "")); /* XXX - when to use maddr? */ if ((agent_init_via(self, tport_primaries(self->sa_tports), 0)) < 0) { error = su_errno(); SU_DEBUG_1(("nta: cannot create Via headers\n")); goto error; } else SU_DEBUG_9(("nta: Via fields initialized\n")); if ((agent_init_contact(self)) < 0) { error = su_errno(); SU_DEBUG_1(("nta: cannot create Contact header\n")); goto error; } else SU_DEBUG_9(("nta: Contact header created\n")); su_free(self->sa_home, url); ta_end(ta); return 0; error: ta_end(ta); su_seterrno(error); return -1; } static int agent_create_master_transport(nta_agent_t *self, tagi_t *tags) { self->sa_tports = tport_tcreate(self, nta_agent_class, self->sa_root, TPTAG_SDWN_ERROR(0), TPTAG_IDLE(1800000), TAG_NEXT(tags)); if (!self->sa_tports) return -1; SU_DEBUG_9(("nta: master transport created\n")); return 0; } /** Initialize @Via headers. */ static int agent_init_via(nta_agent_t *self, tport_t *primaries, int use_maddr) { sip_via_t *via = NULL, *new_via, *dup_via, *v, **vv = &via; sip_via_t *new_vias, **next_new_via, *new_publics, **next_new_public; tport_t *tp; su_addrinfo_t const *ai; su_home_t autohome[SU_HOME_AUTO_SIZE(2048)]; su_home_auto(autohome, sizeof autohome); self->sa_tport_ip4 = 0; self->sa_tport_ip6 = 0; self->sa_tport_udp = 0; self->sa_tport_tcp = 0; self->sa_tport_sctp = 0; self->sa_tport_tls = 0; /* Set via fields for the tports */ for (tp = primaries; tp; tp = tport_next(tp)) { int maddr, first_via; tp_name_t tpn[1]; char const *comp = NULL; *tpn = *tport_name(tp); assert(tpn->tpn_proto); assert(tpn->tpn_canon); assert(tpn->tpn_host); assert(tpn->tpn_port); #if 0 if (getenv("SIP_UDP_CONNECT") && strcmp(tpn->tpn_proto, "udp") == 0) tport_set_params(tp, TPTAG_CONNECT(1), TAG_END()); #endif if (tport_has_ip4(tp)) self->sa_tport_ip4 = 1; #if SU_HAVE_IN6 if (tport_has_ip6(tp)) self->sa_tport_ip6 = 1; #endif if (su_casematch(tpn->tpn_proto, "udp")) self->sa_tport_udp = 1; else if (su_casematch(tpn->tpn_proto, "tcp")) self->sa_tport_tcp = 1; else if (su_casematch(tpn->tpn_proto, "sctp")) self->sa_tport_sctp = 1; if (tport_has_tls(tp)) self->sa_tport_tls = 1; first_via = 1; ai = tport_get_address(tp); for (; ai; ai = ai->ai_next) { char host[TPORT_HOSTPORTSIZE] = ""; char sport[8]; char const *canon = ai->ai_canonname; su_sockaddr_t *su = (void *)ai->ai_addr; int port; if (su) { su_inet_ntop(su->su_family, SU_ADDR(su), host, sizeof host); maddr = use_maddr && !su_casematch(canon, host); port = ntohs(su->su_port); } else { msg_random_token(host, 16, NULL, 0); canon = strcat(host, ".is.invalid"); maddr = 0; port = 0; } if (su_casenmatch(tpn->tpn_proto, "tls", 3) ? port == SIPS_DEFAULT_PORT : port == SIP_DEFAULT_PORT) port = 0; snprintf(sport, sizeof sport, ":%u", port); comp = tpn->tpn_comp; SU_DEBUG_9(("nta: agent_init_via: " "%s/%s %s%s%s%s%s%s (%s)\n", SIP_VERSION_CURRENT, tpn->tpn_proto, canon, port ? sport : "", maddr ? ";maddr=" : "", maddr ? host : "", comp ? ";comp=" : "", comp ? comp : "", tpn->tpn_ident ? tpn->tpn_ident : "*")); v = sip_via_format(autohome, "%s/%s %s%s%s%s%s%s", SIP_VERSION_CURRENT, tpn->tpn_proto, canon, port ? sport : "", maddr ? ";maddr=" : "", maddr ? host : "", comp ? ";comp=" : "", comp ? comp : ""); if (v == NULL) goto error; v->v_comment = tpn->tpn_ident; v->v_common->h_data = tp; /* Nasty trick */ *vv = v; vv = &(*vv)->v_next; } } /* Duplicate the list bind to the transports */ new_via = sip_via_dup(self->sa_home, via); /* Duplicate the complete list shown to the application */ dup_via = sip_via_dup(self->sa_home, via); if (via && (!new_via || !dup_via)) { msg_header_free(self->sa_home, (void *)new_via); msg_header_free(self->sa_home, (void *)dup_via); goto error; } new_vias = NULL, next_new_via = &new_vias; new_publics = NULL, next_new_public = &new_publics; /* Set via field magic for the tports */ for (tp = primaries; tp; tp = tport_next(tp)) { assert(via->v_common->h_data == tp); v = tport_magic(tp); tport_set_magic(tp, new_via); msg_header_free(self->sa_home, (void *)v); if (tport_is_public(tp)) *next_new_public = dup_via; else *next_new_via = dup_via; while (via->v_next && via->v_next->v_common->h_data == tp) via = via->v_next, new_via = new_via->v_next, dup_via = dup_via->v_next; via = via->v_next; /* Break the link in via list between transports */ vv = &new_via->v_next, new_via = *vv, *vv = NULL; vv = &dup_via->v_next, dup_via = *vv, *vv = NULL; if (tport_is_public(tp)) while (*next_new_public) next_new_public = &(*next_new_public)->v_next; else while (*next_new_via) next_new_via = &(*next_new_via)->v_next; } assert(dup_via == NULL); assert(new_via == NULL); if (self->sa_tport_udp) agent_set_udp_params(self, self->sa_udp_mtu); v = self->sa_vias; self->sa_vias = new_vias; msg_header_free(self->sa_home, (void *)v); v = self->sa_public_vias; self->sa_public_vias = new_publics; msg_header_free(self->sa_home, (void *)v); su_home_deinit(autohome); return 0; error: su_home_deinit(autohome); return -1; } /** Initialize main contact header. */ static int agent_init_contact(nta_agent_t *self) { sip_via_t const *v1, *v2; char const *tp; if (self->sa_contact) return 0; for (v1 = self->sa_vias ? self->sa_vias : self->sa_public_vias; v1; v1 = v1->v_next) { if (host_is_ip_address(v1->v_host)) { if (!host_is_local(v1->v_host)) break; } else if (!host_has_domain_invalid(v1->v_host)) { break; } } if (v1 == NULL) v1 = self->sa_vias ? self->sa_vias : self->sa_public_vias; if (!v1) return -1; tp = strrchr(v1->v_protocol, '/'); if (!tp++) return -1; v2 = v1->v_next; if (v2 && su_casematch(v1->v_host, v2->v_host) && su_casematch(v1->v_port, v2->v_port)) { char const *p1 = v1->v_protocol, *p2 = v2->v_protocol; if (!su_casematch(p1, sip_transport_udp)) p1 = v2->v_protocol, p2 = v1->v_protocol; if (su_casematch(p1, sip_transport_udp) && su_casematch(p2, sip_transport_tcp)) /* Do not include transport if we have both UDP and TCP */ tp = NULL; } self->sa_contact = sip_contact_create_from_via_with_transport(self->sa_home, v1, NULL, tp); if (!self->sa_contact) return -1; agent_tag_init(self); return 0; } /** Return @Via line corresponging to tport. */ static sip_via_t const *agent_tport_via(tport_t *tport) { sip_via_t *v = tport_magic(tport); while (v && v->v_next) v = v->v_next; return v; } /** Insert @Via to a request message */ static int outgoing_insert_via(nta_outgoing_t *orq, sip_via_t const *via) { nta_agent_t *self = orq->orq_agent; msg_t *msg = orq->orq_request; sip_t *sip = sip_object(msg); char const *branch = orq->orq_via_branch; int already = orq->orq_user_via || orq->orq_via_added; int user_via = orq->orq_user_via; sip_via_t *v; int clear = 0; assert(sip); assert(via); if (already && sip->sip_via) { /* Use existing @Via */ v = sip->sip_via; } else if (msg && via && sip->sip_request && (v = sip_via_copy(msg_home(msg), via))) { if (msg_header_insert(msg, (msg_pub_t *)sip, (msg_header_t *)v) < 0) return -1; orq->orq_via_added = 1; } else return -1; if (!v->v_rport && ((self->sa_rport && v->v_protocol == sip_transport_udp) || (self->sa_tcp_rport && v->v_protocol == sip_transport_tcp) || (self->sa_tls_rport && v->v_protocol == sip_transport_tls))) msg_header_add_param(msg_home(msg), v->v_common, "rport"); if (!orq->orq_tpn->tpn_comp) msg_header_remove_param(v->v_common, "comp"); if (branch && branch != v->v_branch) { char const *bvalue = branch + strcspn(branch, "="); if (*bvalue) bvalue++; if (!v->v_branch || !su_casematch(bvalue, v->v_branch)) msg_header_replace_param(msg_home(msg), v->v_common, branch); } if (!su_casematch(via->v_protocol, v->v_protocol)) clear = 1, v->v_protocol = via->v_protocol; /* XXX - should we do this? */ if ((!user_via || !v->v_host) && !su_strmatch(via->v_host, v->v_host)) clear = 1, v->v_host = via->v_host; if ((!user_via || !v->v_port || /* Replace port in user Via only if we use udp and no rport */ (v->v_protocol == sip_transport_udp && !v->v_rport && !orq->orq_stateless)) && !su_strmatch(via->v_port, v->v_port)) clear = 1, v->v_port = via->v_port; if (clear) msg_fragment_clear_chain((msg_header_t *)v); return 0; } /** Get destination name from @Via. * * If @a using_rport is non-null, try rport. * If *using_rport is non-zero, try rport even if <protocol> is not UDP. * If <protocol> is UDP, set *using_rport to zero. */ static int nta_tpn_by_via(tp_name_t *tpn, sip_via_t const *v, int *using_rport) { if (!v) return -1; tpn->tpn_proto = sip_via_transport(v); tpn->tpn_canon = v->v_host; if (v->v_maddr) tpn->tpn_host = v->v_maddr; else if (v->v_received) tpn->tpn_host = v->v_received; else tpn->tpn_host = v->v_host; tpn->tpn_port = sip_via_port(v, using_rport); tpn->tpn_comp = v->v_comp; tpn->tpn_ident = NULL; return 0; } /** Get transport name from URL. */ static int nta_tpn_by_url(su_home_t *home, tp_name_t *tpn, char const **scheme, char const **port, url_string_t const *us) { url_t url[1]; isize_t n; char *b; n = url_xtra(us->us_url); b = su_alloc(home, n); if (b == NULL || url_dup(b, n, url, us->us_url) < 0) { su_free(home, b); return -1; } if (url->url_type != url_sip && url->url_type != url_sips && url->url_type != url_im && url->url_type != url_pres) { su_free(home, b); return -1; } SU_DEBUG_7(("nta: selecting scheme %s\n", url->url_scheme)); *scheme = url->url_scheme; tpn->tpn_proto = NULL; tpn->tpn_canon = url->url_host; tpn->tpn_host = url->url_host; if (url->url_params) { for (b = (char *)url->url_params; b[0]; b += n) { n = strcspn(b, ";"); if (n > 10 && su_casenmatch(b, "transport=", 10)) tpn->tpn_proto = b + 10; else if (n > 5 && su_casenmatch(b, "comp=", 5)) tpn->tpn_comp = b + 5; else if (n > 6 && su_casenmatch(b, "maddr=", 6)) tpn->tpn_host = b + 6; if (b[n]) b[n++] = '\0'; } } if ((*port = url->url_port)) tpn->tpn_port = url->url_port; tpn->tpn_ident = NULL; if (tpn->tpn_proto) return 1; if (su_casematch(url->url_scheme, "sips")) tpn->tpn_proto = "tls"; else tpn->tpn_proto = "*"; return 0; } /** Handle transport errors. */ static void agent_tp_error(nta_agent_t *agent, tport_t *tport, int errcode, char const *remote) { su_llog(nta_log, 1, "nta_agent: tport: %s%s%s\n", remote ? remote : "", remote ? ": " : "", su_strerror(errcode)); } /** Handle updated transport addresses */ static void agent_update_tport(nta_agent_t *self, tport_t *tport) { /* Initialize local Vias first */ agent_init_via(self, tport_primaries(self->sa_tports), 0); if (self->sa_update_tport) { self->sa_update_tport(self->sa_update_magic, self); } else { /* XXX - we should do something else? */ SU_DEBUG_3(("%s(%p): %s\n", "nta", (void *)self, "transport address updated")); } } /* ====================================================================== */ /* 3) Message dispatch */ static void agent_recv_request(nta_agent_t *agent, msg_t *msg, sip_t *sip, tport_t *tport); static int agent_check_request_via(nta_agent_t *agent, msg_t *msg, sip_t *sip, sip_via_t *v, tport_t *tport); static int agent_aliases(nta_agent_t const *, url_t [], tport_t *); static void agent_recv_response(nta_agent_t*, msg_t *, sip_t *, sip_via_t *, tport_t*); static void agent_recv_garbage(nta_agent_t*, msg_t*, tport_t*); /** Handle incoming message. */ static void agent_recv_message(nta_agent_t *agent, tport_t *tport, msg_t *msg, sip_via_t *tport_via, su_time_t now) { sip_t *sip = sip_object(msg); agent->sa_millisec = su_time_ms(agent->sa_now = now); if (sip && sip->sip_request) { agent_recv_request(agent, msg, sip, tport); } else if (sip && sip->sip_status) { agent_recv_response(agent, msg, sip, tport_via, tport); } else { agent_recv_garbage(agent, msg, tport); } agent->sa_millisec = 0; } /** @internal Handle incoming requests. */ static void agent_recv_request(nta_agent_t *agent, msg_t *msg, sip_t *sip, tport_t *tport) { nta_leg_t *leg; nta_incoming_t *irq, *merge = NULL, *ack = NULL, *cancel = NULL; sip_method_t method = sip->sip_request->rq_method; char const *method_name = sip->sip_request->rq_method_name; url_t url[1]; unsigned cseq = sip->sip_cseq ? sip->sip_cseq->cs_seq : 0; int insane, errors, stream; agent->sa_stats->as_recv_msg++; agent->sa_stats->as_recv_request++; SU_DEBUG_5(("nta: received %s " URL_PRINT_FORMAT " %s (CSeq %u)\n", method_name, URL_PRINT_ARGS(sip->sip_request->rq_url), sip->sip_request->rq_version, cseq)); if (agent->sa_drop_prob && !tport_is_reliable(tport)) { if ((unsigned)su_randint(0, 1000) < agent->sa_drop_prob) { SU_DEBUG_5(("nta: %s (%u) is %s\n", method_name, cseq, "dropped simulating packet loss")); agent->sa_stats->as_drop_request++; msg_destroy(msg); return; } } stream = tport_is_stream(tport); /* Try to use compression on reverse direction if @Via has comp=sigcomp */ if (stream && sip->sip_via && sip->sip_via->v_comp && tport_can_send_sigcomp(tport) && tport_name(tport)->tpn_comp == NULL && tport_has_compression(tport_parent(tport), sip->sip_via->v_comp)) { tport_set_compression(tport, sip->sip_via->v_comp); } if (sip->sip_flags & MSG_FLG_TOOLARGE) { SU_DEBUG_5(("nta: %s (%u) is %s\n", method_name, cseq, sip_413_Request_too_large)); agent->sa_stats->as_bad_request++; mreply(agent, NULL, SIP_413_REQUEST_TOO_LARGE, msg, tport, 1, stream, NULL, TAG_END()); return; } insane = 0; if (agent->sa_bad_req_mask != ~0U) errors = msg_extract_errors(msg) & agent->sa_bad_req_mask; else errors = sip->sip_error != NULL; if (errors || (sip->sip_flags & MSG_FLG_ERROR) /* Fatal error */ || (insane = (sip_sanity_check(sip) < 0))) { sip_header_t const *h; char const *badname = NULL, *phrase; agent->sa_stats->as_bad_message++; agent->sa_stats->as_bad_request++; if (insane) SU_DEBUG_5(("nta: %s (%u) %s\n", method_name, cseq, "failed sanity check")); for (h = (sip_header_t const *)sip->sip_error; h; h = h->sh_next) { char const *bad; if (h->sh_class == sip_error_class) bad = h->sh_error->er_name; else bad = h->sh_class->hc_name; if (bad) SU_DEBUG_5(("nta: %s has bad %s header\n", method_name, bad)); if (!badname) badname = bad; } if (sip->sip_via && method != sip_method_ack) { msg_t *reply = nta_msg_create(agent, 0); agent_check_request_via(agent, msg, sip, sip->sip_via, tport); if (badname && reply) phrase = su_sprintf(msg_home(reply), "Bad %s Header", badname); else phrase = sip_400_Bad_request; SU_DEBUG_5(("nta: %s (%u) is %s\n", method_name, cseq, phrase)); mreply(agent, reply, 400, phrase, msg, tport, 1, stream, NULL, TAG_END()); } else { msg_destroy(msg); if (stream) /* Send FIN */ tport_shutdown(tport, 1); } return; } if (!su_casematch(sip->sip_request->rq_version, sip_version_2_0)) { agent->sa_stats->as_bad_request++; agent->sa_stats->as_bad_message++; SU_DEBUG_5(("nta: bad version %s for %s (%u)\n", sip->sip_request->rq_version, method_name, cseq)); mreply(agent, NULL, SIP_505_VERSION_NOT_SUPPORTED, msg, tport, 0, stream, NULL, TAG_END()); return; } if (agent_check_request_via(agent, msg, sip, sip->sip_via, tport) < 0) { agent->sa_stats->as_bad_message++; agent->sa_stats->as_bad_request++; SU_DEBUG_5(("nta: %s (%u) %s\n", method_name, cseq, "has invalid Via")); msg_destroy(msg); return; } /* First, try existing incoming requests */ irq = incoming_find(agent, sip, sip->sip_via, agent->sa_merge_482 && !sip->sip_to->a_tag && method != sip_method_ack ? &merge : NULL, method == sip_method_ack ? &ack : NULL, method == sip_method_cancel ? &cancel : NULL); if (irq) { /* Match - this is a retransmission */ SU_DEBUG_5(("nta: %s (%u) going to existing %s transaction\n", method_name, cseq, irq->irq_rq->rq_method_name)); if (incoming_recv(irq, msg, sip, tport) >= 0) return; } else if (ack) { SU_DEBUG_5(("nta: %s (%u) is going to %s (%u)\n", method_name, cseq, ack->irq_cseq->cs_method_name, ack->irq_cseq->cs_seq)); if (incoming_ack(ack, msg, sip, tport) >= 0) return; } else if (cancel) { SU_DEBUG_5(("nta: %s (%u) is going to %s (%u)\n", method_name, cseq, cancel->irq_cseq->cs_method_name, cancel->irq_cseq->cs_seq)); if (incoming_cancel(cancel, msg, sip, tport) >= 0) return; } else if (merge) { SU_DEBUG_5(("nta: %s (%u) %s\n", method_name, cseq, "is a merged request")); request_merge(agent, msg, sip, tport, merge->irq_tag); return; } if (method == sip_method_prack && sip->sip_rack) { nta_reliable_t *rel = reliable_find(agent, sip); if (rel) { SU_DEBUG_5(("nta: %s (%u) is going to %s (%u)\n", method_name, cseq, rel->rel_irq->irq_cseq->cs_method_name, rel->rel_irq->irq_cseq->cs_seq)); reliable_recv(rel, msg, sip, tport); return; } } *url = *sip->sip_request->rq_url; url->url_params = NULL; agent_aliases(agent, url, tport); /* canonize urls */ if ((leg = leg_find(agent, method_name, url, sip->sip_call_id, sip->sip_from->a_tag, sip->sip_to->a_tag))) { /* Try existing dialog */ SU_DEBUG_5(("nta: %s (%u) %s\n", method_name, cseq, "going to existing leg")); leg_recv(leg, msg, sip, tport); return; } else if (!agent->sa_is_stateless && (leg = dst_find(agent, url, method_name))) { /* Dialogless legs - let application process transactions statefully */ SU_DEBUG_5(("nta: %s (%u) %s\n", method_name, cseq, "going to a dialogless leg")); leg_recv(leg, msg, sip, tport); } else if (!agent->sa_is_stateless && (leg = agent->sa_default_leg)) { if (method == sip_method_invite && agent->sa_in.proceeding->q_length >= agent->sa_max_proceeding) { SU_DEBUG_5(("nta: proceeding queue full for %s (%u)\n", method_name, cseq)); mreply(agent, NULL, SIP_503_SERVICE_UNAVAILABLE, msg, tport, 0, 0, NULL, TAG_END()); return; } else { SU_DEBUG_5(("nta: %s (%u) %s\n", method_name, cseq, "going to a default leg")); leg_recv(leg, msg, sip, tport); } } else if (agent->sa_callback) { /* Stateless processing for request */ agent->sa_stats->as_trless_request++; SU_DEBUG_5(("nta: %s (%u) %s\n", method_name, cseq, "to message callback")); (void)agent->sa_callback(agent->sa_magic, agent, msg, sip); } else { agent->sa_stats->as_trless_request++; SU_DEBUG_5(("nta: %s (%u) %s\n", method_name, cseq, "not processed by application: returning 501")); if (method != sip_method_ack) mreply(agent, NULL, SIP_501_NOT_IMPLEMENTED, msg, tport, 0, 0, NULL, TAG_END()); else msg_destroy(msg); } } /** Check @Via header. * */ static int agent_check_request_via(nta_agent_t *agent, msg_t *msg, sip_t *sip, sip_via_t *v, tport_t *tport) { enum { receivedlen = sizeof("received=") - 1 }; char received[receivedlen + TPORT_HOSTPORTSIZE]; char *hostport = received + receivedlen; char const *rport; su_sockaddr_t const *from; sip_via_t const *tpv = agent_tport_via(tport); assert(tport); assert(msg); assert(sip); assert(sip->sip_request); assert(tpv); from = msg_addr(msg); if (v == NULL) { /* Make up a via line */ v = sip_via_format(msg_home(msg), "SIP/2.0/%s %s", tport_name(tport)->tpn_proto, tport_hostport(hostport, TPORT_HOSTPORTSIZE, from, 1)); msg_header_insert(msg, (msg_pub_t *)sip, (msg_header_t *)v); return v ? 0 : -1; } if (!su_strmatch(v->v_protocol, tpv->v_protocol)) { tport_hostport(hostport, TPORT_HOSTPORTSIZE, from, 1); SU_DEBUG_1(("nta: Via check: invalid transport \"%s\" from %s\n", v->v_protocol, hostport)); return -1; } if (v->v_received) { /* Nasty, nasty */ tport_hostport(hostport, TPORT_HOSTPORTSIZE, from, 1); SU_DEBUG_1(("nta: Via check: extra received=%s from %s\n", v->v_received, hostport)); msg_header_remove_param(v->v_common, "received"); } if (!tport_hostport(hostport, TPORT_HOSTPORTSIZE, from, 0)) return -1; if (!su_casematch(hostport, v->v_host)) { size_t rlen; /* Add the "received" field */ memcpy(received, "received=", receivedlen); if (hostport[0] == '[') { rlen = strlen(hostport + 1) - 1; memmove(hostport, hostport + 1, rlen); hostport[rlen] = '\0'; } msg_fragment_clear_chain((msg_header_t *)v); msg_header_replace_param(msg_home(msg), v->v_common, su_strdup(msg_home(msg), received)); SU_DEBUG_5(("nta: Via check: %s\n", received)); } if (!agent->sa_server_rport) { /*Xyzzy*/; } else if (v->v_rport) { rport = su_sprintf(msg_home(msg), "rport=%u", ntohs(from->su_port)); msg_header_replace_param(msg_home(msg), v->v_common, rport); } else if (tport_is_tcp(tport)) { rport = su_sprintf(msg_home(msg), "rport=%u", ntohs(from->su_port)); msg_header_replace_param(msg_home(msg), v->v_common, rport); } else if (agent->sa_server_rport == 2 || (agent->sa_server_rport == 3 && sip && sip->sip_user_agent && su_casenmatch(sip->sip_user_agent->g_string, "Polycom", 7))) { rport = su_sprintf(msg_home(msg), "rport=%u", ntohs(from->su_port)); msg_header_replace_param(msg_home(msg), v->v_common, rport); } return 0; } /** @internal Handle aliases of local node. * * Return true if @a url is modified. */ static int agent_aliases(nta_agent_t const *agent, url_t url[], tport_t *tport) { sip_contact_t *m; sip_via_t const *lv; char const *tport_port = ""; if (!url->url_host) return 0; if (tport) tport_port = tport_name(tport)->tpn_port; assert(tport_port); for (m = agent->sa_aliases ? agent->sa_aliases : agent->sa_contact; m; m = m->m_next) { if (url->url_type != m->m_url->url_type) continue; if (host_cmp(url->url_host, m->m_url->url_host)) continue; if (url->url_port == NULL) break; if (m->m_url->url_port) { if (strcmp(url->url_port, m->m_url->url_port)) continue; } else { if (strcmp(url->url_port, tport_port)) continue; } break; } if (!m) return 0; SU_DEBUG_7(("nta: canonizing " URL_PRINT_FORMAT " with %s\n", URL_PRINT_ARGS(url), agent->sa_aliases ? "aliases" : "contact")); url->url_host = "%"; if (agent->sa_aliases) { url->url_type = agent->sa_aliases->m_url->url_type; url->url_scheme = agent->sa_aliases->m_url->url_scheme; url->url_port = agent->sa_aliases->m_url->url_port; return 1; } else { /* Canonize the request URL port */ if (tport) { lv = agent_tport_via(tport_parent(tport)); assert(lv); if (lv->v_port) /* Add non-default port */ url->url_port = lv->v_port; return 1; } if (su_strmatch(url->url_port, url_port_default((enum url_type_e)url->url_type)) || su_strmatch(url->url_port, "")) /* Remove default or empty port */ url->url_port = NULL; return 0; } } /** @internal Handle incoming responses. */ static void agent_recv_response(nta_agent_t *agent, msg_t *msg, sip_t *sip, sip_via_t *tport_via, tport_t *tport) { int status = sip->sip_status->st_status; int errors; char const *phrase = sip->sip_status->st_phrase; char const *method = sip->sip_cseq ? sip->sip_cseq->cs_method_name : "<UNKNOWN>"; uint32_t cseq = sip->sip_cseq ? sip->sip_cseq->cs_seq : 0; nta_outgoing_t *orq; agent->sa_stats->as_recv_msg++; agent->sa_stats->as_recv_response++; SU_DEBUG_5(("nta: received %03d %s for %s (%u)\n", status, phrase, method, cseq)); if (agent->sa_drop_prob && !tport_is_reliable(tport)) { if ((unsigned)su_randint(0, 1000) < agent->sa_drop_prob) { SU_DEBUG_5(("nta: %03d %s %s\n", status, phrase, "dropped simulating packet loss")); agent->sa_stats->as_drop_response++; msg_destroy(msg); return; } } if (agent->sa_bad_resp_mask) errors = msg_extract_errors(msg) & agent->sa_bad_resp_mask; else errors = sip->sip_error != NULL; if (errors || sip_sanity_check(sip) < 0) { sip_header_t const *h; agent->sa_stats->as_bad_response++; agent->sa_stats->as_bad_message++; SU_DEBUG_5(("nta: %03d %s %s\n", status, phrase, errors ? "has fatal syntax errors" : "failed sanity check")); for (h = (sip_header_t const *)sip->sip_error; h; h = h->sh_next) { if (h->sh_class->hc_name) { SU_DEBUG_5(("nta: %03d has bad %s header\n", status, h->sh_class->hc_name)); } } msg_destroy(msg); return; } if (!su_casematch(sip->sip_status->st_version, sip_version_2_0)) { agent->sa_stats->as_bad_response++; agent->sa_stats->as_bad_message++; SU_DEBUG_5(("nta: bad version %s %03d %s\n", sip->sip_status->st_version, status, phrase)); msg_destroy(msg); return; } if (sip->sip_cseq->cs_method == sip_method_ack) { /* Drop response messages to ACK */ agent->sa_stats->as_bad_response++; agent->sa_stats->as_bad_message++; SU_DEBUG_5(("nta: %03d %s %s\n", status, phrase, "is response to ACK")); msg_destroy(msg); return; } /* XXX - should check if msg should be discarded based on via? */ if ((orq = outgoing_find(agent, msg, sip, sip->sip_via))) { SU_DEBUG_5(("nta: %03d %s %s\n", status, phrase, "is going to a transaction")); if (outgoing_recv(orq, status, msg, sip) == 0) return; } agent->sa_stats->as_trless_response++; if ((orq = agent->sa_default_outgoing)) { SU_DEBUG_5(("nta: %03d %s %s\n", status, phrase, "to the default transaction")); outgoing_default_recv(orq, status, msg, sip); return; } else if (agent->sa_callback) { SU_DEBUG_5(("nta: %03d %s %s\n", status, phrase, "to message callback")); /* * Store message and transport to hook for the duration of the callback * so that the transport can be obtained by nta_transport(). */ (void)agent->sa_callback(agent->sa_magic, agent, msg, sip); return; } if (sip->sip_cseq->cs_method == sip_method_invite && 200 <= sip->sip_status->st_status && sip->sip_status->st_status < 300 /* Exactly one Via header, belonging to us */ && sip->sip_via && !sip->sip_via->v_next && agent_has_via(agent, sip->sip_via)) { agent->sa_stats->as_trless_200++; } SU_DEBUG_5(("nta: %03d %s %s\n", status, phrase, "was discarded")); msg_destroy(msg); } /** @internal Agent receives garbage */ static void agent_recv_garbage(nta_agent_t *agent, msg_t *msg, tport_t *tport) { agent->sa_stats->as_recv_msg++; agent->sa_stats->as_bad_message++; #if SU_DEBUG >= 3 if (nta_log->log_level >= 3) { tp_name_t tpn[1]; tport_delivered_from(tport, msg, tpn); SU_DEBUG_3(("nta_agent: received garbage from " TPN_FORMAT "\n", TPN_ARGS(tpn))); } #endif msg_destroy(msg); } /* ====================================================================== */ /* 4) Message handling - create, complete, destroy */ /** Create a new message belonging to the agent */ msg_t *nta_msg_create(nta_agent_t *agent, int flags) { msg_t *msg; if (agent == NULL) return su_seterrno(EINVAL), NULL; msg = msg_create(agent->sa_mclass, agent->sa_flags | flags); if (agent->sa_preload) su_home_preload(msg_home(msg), 1, agent->sa_preload); return msg; } /** Create a new message for transport */ msg_t *nta_msg_create_for_transport(nta_agent_t *agent, int flags, char const data[], usize_t dlen, tport_t const *tport, tp_client_t *via) { msg_t *msg = msg_create(agent->sa_mclass, agent->sa_flags | flags); msg_maxsize(msg, agent->sa_maxsize); if (agent->sa_preload) su_home_preload(msg_home(msg), 1, dlen + agent->sa_preload); return msg; } /** Complete a message. */ int nta_msg_complete(msg_t *msg) { return sip_complete_message(msg); } /** Discard a message */ void nta_msg_discard(nta_agent_t *agent, msg_t *msg) { msg_destroy(msg); } /** Check if the headers are from response generated locally by NTA. */ int nta_sip_is_internal(sip_t const *sip) { return sip == NULL /* No message generated */ || (sip->sip_flags & NTA_INTERNAL_MSG) == NTA_INTERNAL_MSG; } /** Check if the message is internally generated by NTA. */ int nta_msg_is_internal(msg_t const *msg) { return msg_get_flags(msg, NTA_INTERNAL_MSG) == NTA_INTERNAL_MSG; } /** Check if the message is internally generated by NTA. * * @deprecated Use nta_msg_is_internal() instead */ int nta_is_internal_msg(msg_t const *msg) { return nta_msg_is_internal(msg); } /* ====================================================================== */ /* 5) Stateless operation */ /**Forward a request or response message. * * @note * The ownership of @a msg is taken over by the function even if the * function fails. */ int nta_msg_tsend(nta_agent_t *agent, msg_t *msg, url_string_t const *u, tag_type_t tag, tag_value_t value, ...) { int retval = -1; ta_list ta; sip_t *sip = sip_object(msg); tp_name_t tpn[1] = {{ NULL }}; char const *what; if (!sip) { msg_destroy(msg); return -1; } what = sip->sip_status ? "nta_msg_tsend(response)" : sip->sip_request ? "nta_msg_tsend(request)" : "nta_msg_tsend()"; ta_start(ta, tag, value); if (sip_add_tl(msg, sip, ta_tags(ta)) < 0) SU_DEBUG_3(("%s: cannot add headers\n", what)); else if (sip->sip_status) { tport_t *tport = NULL; int *use_rport = NULL; int retry_without_rport = 0; struct sigcomp_compartment *cc; cc = NONE; if (agent->sa_server_rport) use_rport = &retry_without_rport, retry_without_rport = 1; tl_gets(ta_args(ta), NTATAG_TPORT_REF(tport), IF_SIGCOMP_TPTAG_COMPARTMENT_REF(cc) /* NTATAG_INCOMPLETE_REF(incomplete), */ TAG_END()); if (!sip->sip_separator && !(sip->sip_separator = sip_separator_create(msg_home(msg)))) SU_DEBUG_3(("%s: cannot create sip_separator\n", what)); else if (msg_serialize(msg, (msg_pub_t *)sip) != 0) SU_DEBUG_3(("%s: sip_serialize() failed\n", what)); else if (!sip_via_remove(msg, sip)) SU_DEBUG_3(("%s: cannot remove Via\n", what)); else if (nta_tpn_by_via(tpn, sip->sip_via, use_rport) < 0) SU_DEBUG_3(("%s: bad via\n", what)); else { if (!tport) tport = tport_by_name(agent->sa_tports, tpn); if (!tport) tport = tport_by_protocol(agent->sa_tports, tpn->tpn_proto); if (retry_without_rport) tpn->tpn_port = sip_via_port(sip->sip_via, NULL); if (tport && tpn->tpn_comp && cc == NONE) cc = agent_compression_compartment(agent, tport, tpn, -1); if (tport_tsend(tport, msg, tpn, IF_SIGCOMP_TPTAG_COMPARTMENT(cc) TPTAG_MTU(INT_MAX), ta_tags(ta), TAG_END())) { agent->sa_stats->as_sent_msg++; agent->sa_stats->as_sent_response++; retval = 0; } else { SU_DEBUG_3(("%s: send fails\n", what)); } } } else { /* Send request */ if (outgoing_create(agent, NULL, NULL, u, NULL, msg_ref(msg), NTATAG_STATELESS(1), ta_tags(ta))) retval = 0; } if (retval == 0) SU_DEBUG_5(("%s\n", what)); ta_end(ta); msg_destroy(msg); return retval; } /** Reply to a request message. * * @param agent nta agent object * @param req_msg request message * @param status status code * @param phrase status phrase (may be NULL if status code is well-known) * @param tag, value, ... optional additional headers terminated by TAG_END() * * @retval 0 when succesful * @retval -1 upon an error * * @note * The ownership of @a msg is taken over by the function even if the * function fails. */ int nta_msg_treply(nta_agent_t *agent, msg_t *req_msg, int status, char const *phrase, tag_type_t tag, tag_value_t value, ...) { int retval; ta_list ta; ta_start(ta, tag, value); retval = mreply(agent, NULL, status, phrase, req_msg, NULL, 0, 0, NULL, ta_tags(ta)); ta_end(ta); return retval; } /**Reply to the request message. * * @note * The ownership of @a msg is taken over by the function even if the * function fails. */ int nta_msg_mreply(nta_agent_t *agent, msg_t *reply, sip_t *sip, int status, char const *phrase, msg_t *req_msg, tag_type_t tag, tag_value_t value, ...) { int retval = -1; ta_list ta; ta_start(ta, tag, value); retval = mreply(agent, reply, status, phrase, req_msg, NULL, 0, 0, NULL, ta_tags(ta)); ta_end(ta); return retval; } static int mreply(nta_agent_t *agent, msg_t *reply, int status, char const *phrase, msg_t *req_msg, tport_t *tport, int incomplete, int sdwn_after, char const *to_tag, tag_type_t tag, tag_value_t value, ...) { ta_list ta; sip_t *sip; int *use_rport = NULL; int retry_without_rport = 0; tp_name_t tpn[1]; int retval = -1; if (!agent) return -1; if (agent->sa_server_rport) use_rport = &retry_without_rport, retry_without_rport = 1; ta_start(ta, tag, value); tl_gets(ta_args(ta), NTATAG_TPORT_REF(tport), TAG_END()); if (reply == NULL) { reply = nta_msg_create(agent, 0); } sip = sip_object(reply); if (!sip) { SU_DEBUG_3(("%s: cannot create response msg\n", __func__)); } else if (sip_add_tl(reply, sip, ta_tags(ta)) < 0) { SU_DEBUG_3(("%s: cannot add user headers\n", __func__)); } else if (complete_response(reply, status, phrase, req_msg) < 0 && !incomplete) { SU_DEBUG_3(("%s: cannot complete message\n", __func__)); } else if (sip->sip_status && sip->sip_status->st_status > 100 && sip->sip_to && !sip->sip_to->a_tag && (to_tag == NONE ? 0 : to_tag != NULL ? sip_to_tag(msg_home(reply), sip->sip_to, to_tag) < 0 : sip_to_tag(msg_home(reply), sip->sip_to, nta_agent_newtag(msg_home(reply), "tag=%s", agent)) < 0)) { SU_DEBUG_3(("%s: cannot add To tag\n", __func__)); } else if (nta_tpn_by_via(tpn, sip->sip_via, use_rport) < 0) { SU_DEBUG_3(("%s: no Via\n", __func__)); } else { struct sigcomp_compartment *cc = NONE; if (tport == NULL) tport = tport_delivered_by(agent->sa_tports, req_msg); if (!tport) { tport_t *primary = tport_by_protocol(agent->sa_tports, tpn->tpn_proto); tport = tport_by_name(primary, tpn); if (!tport) tport = primary; } if (retry_without_rport) tpn->tpn_port = sip_via_port(sip->sip_via, NULL); if (tport && tpn->tpn_comp) { tl_gets(ta_args(ta), TPTAG_COMPARTMENT_REF(cc), /* XXX - should also check ntatag_sigcomp_close() */ TAG_END()); if (cc == NONE) cc = agent_compression_compartment(agent, tport, tpn, -1); if (cc != NULL && cc != NONE && tport_delivered_with_comp(tport, req_msg, NULL) != -1) { agent_accept_compressed(agent, req_msg, cc); } } if (tport_tsend(tport, reply, tpn, IF_SIGCOMP_TPTAG_COMPARTMENT(cc) TPTAG_MTU(INT_MAX), TPTAG_SDWN_AFTER(sdwn_after), ta_tags(ta))) { agent->sa_stats->as_sent_msg++; agent->sa_stats->as_sent_response++; retval = 0; /* Success! */ } else { SU_DEBUG_3(("%s: send fails\n", __func__)); } } msg_destroy(reply); msg_destroy(req_msg); ta_end(ta); return retval; } /** Add headers from the request to the response message. */ static int complete_response(msg_t *response, int status, char const *phrase, msg_t *request) { su_home_t *home = msg_home(response); sip_t *response_sip = sip_object(response); sip_t const *request_sip = sip_object(request); int incomplete = 0; if (!response_sip || !request_sip || !request_sip->sip_request) return -1; if (!response_sip->sip_status) response_sip->sip_status = sip_status_create(home, status, phrase, NULL); if (!response_sip->sip_via) response_sip->sip_via = sip_via_dup(home, request_sip->sip_via); if (!response_sip->sip_from) response_sip->sip_from = sip_from_dup(home, request_sip->sip_from); if (!response_sip->sip_to) response_sip->sip_to = sip_to_dup(home, request_sip->sip_to); if (!response_sip->sip_call_id) response_sip->sip_call_id = sip_call_id_dup(home, request_sip->sip_call_id); if (!response_sip->sip_cseq) response_sip->sip_cseq = sip_cseq_dup(home, request_sip->sip_cseq); if (!response_sip->sip_record_route && request_sip->sip_record_route) sip_add_dup(response, response_sip, (void*)request_sip->sip_record_route); incomplete = sip_complete_message(response) < 0; msg_serialize(response, (msg_pub_t *)response_sip); if (incomplete || !response_sip->sip_status || !response_sip->sip_via || !response_sip->sip_from || !response_sip->sip_to || !response_sip->sip_call_id || !response_sip->sip_cseq || !response_sip->sip_content_length || !response_sip->sip_separator || (request_sip->sip_record_route && !response_sip->sip_record_route)) return -1; return 0; } /** ACK and BYE an unknown 200 OK response to INVITE. * * A UAS may still return a 2XX series response to client request after the * client transactions has been terminated. In that case, the UAC can not * really accept the call. This function was used to accept and immediately * terminate such a call. * * @deprecated This was a bad idea: see sf.net bug #1750691. It can be used * to amplify DoS attacks. Let UAS take care of retransmission timeout and * let it terminate the session. As of @VERSION_1_12_7, this function just * returns -1. */ int nta_msg_ackbye(nta_agent_t *agent, msg_t *msg) { sip_t *sip = sip_object(msg); msg_t *amsg = nta_msg_create(agent, 0); sip_t *asip = sip_object(amsg); msg_t *bmsg = NULL; sip_t *bsip; url_string_t const *ruri; nta_outgoing_t *ack = NULL, *bye = NULL; sip_cseq_t *cseq; sip_request_t *rq; sip_route_t *route = NULL, *r, r0[1]; su_home_t *home = msg_home(amsg); if (asip == NULL) return -1; sip_add_tl(amsg, asip, SIPTAG_TO(sip->sip_to), SIPTAG_FROM(sip->sip_from), SIPTAG_CALL_ID(sip->sip_call_id), TAG_END()); if (sip->sip_contact) { ruri = (url_string_t const *)sip->sip_contact->m_url; } else { ruri = (url_string_t const *)sip->sip_to->a_url; } /* Reverse (and fix) record route */ route = sip_route_reverse(home, sip->sip_record_route); if (route && !url_has_param(route->r_url, "lr")) { for (r = route; r->r_next; r = r->r_next) ; /* Append r-uri */ *sip_route_init(r0)->r_url = *ruri->us_url; r->r_next = sip_route_dup(home, r0); /* Use topmost route as request-uri */ ruri = (url_string_t const *)route->r_url; route = route->r_next; } msg_header_insert(amsg, (msg_pub_t *)asip, (msg_header_t *)route); bmsg = msg_copy(amsg); bsip = sip_object(bmsg); if (!(cseq = sip_cseq_create(home, sip->sip_cseq->cs_seq, SIP_METHOD_ACK))) goto err; else msg_header_insert(amsg, (msg_pub_t *)asip, (msg_header_t *)cseq); if (!(rq = sip_request_create(home, SIP_METHOD_ACK, ruri, NULL))) goto err; else msg_header_insert(amsg, (msg_pub_t *)asip, (msg_header_t *)rq); if (!(ack = nta_outgoing_mcreate(agent, NULL, NULL, NULL, amsg, NTATAG_ACK_BRANCH(sip->sip_via->v_branch), NTATAG_STATELESS(1), TAG_END()))) goto err; else nta_outgoing_destroy(ack); /* Fire and forget */ home = msg_home(bmsg); if (!(cseq = sip_cseq_create(home, 0x7fffffff, SIP_METHOD_BYE))) goto err; else msg_header_insert(bmsg, (msg_pub_t *)bsip, (msg_header_t *)cseq); if (!(rq = sip_request_create(home, SIP_METHOD_BYE, ruri, NULL))) goto err; else msg_header_insert(bmsg, (msg_pub_t *)bsip, (msg_header_t *)rq); if (!(bye = nta_outgoing_mcreate(agent, NULL, NULL, NULL, bmsg, NTATAG_STATELESS(1), TAG_END()))) goto err; else nta_outgoing_destroy(bye); /* Fire and forget */ msg_destroy(msg); return 0; err: msg_destroy(amsg); msg_destroy(bmsg); return -1; } /**Complete a request with values from dialog. * * Complete a request message @a msg belonging to a dialog associated with * @a leg. It increments the local @CSeq value, adds @CallID, @To, @From and * @Route headers (if there is such headers present in @a leg), and creates * a new request line object from @a method, @a method_name and @a * request_uri. * * @param msg pointer to a request message object * @param leg pointer to a #nta_leg_t object * @param method request method number or #sip_method_unknown * @param method_name method name (if @a method == #sip_method_unknown) * @param request_uri request URI * * If @a request_uri contains query part, the query part is converted as SIP * headers and added to the request. * * @retval 0 when successful * @retval -1 upon an error * * @sa nta_outgoing_mcreate(), nta_outgoing_tcreate() */ int nta_msg_request_complete(msg_t *msg, nta_leg_t *leg, sip_method_t method, char const *method_name, url_string_t const *request_uri) { su_home_t *home = msg_home(msg); sip_t *sip = sip_object(msg); sip_to_t const *to; uint32_t seq; url_t reg_url[1]; url_string_t const *original = request_uri; if (!leg || !msg || !sip) return -1; if (!sip->sip_route && leg->leg_route) { if (leg->leg_loose_route) { if (leg->leg_target) { request_uri = (url_string_t *)leg->leg_target->m_url; } sip->sip_route = sip_route_dup(home, leg->leg_route); } else { sip_route_t **rr; request_uri = (url_string_t *)leg->leg_route->r_url; sip->sip_route = sip_route_dup(home, leg->leg_route->r_next); for (rr = &sip->sip_route; *rr; rr = &(*rr)->r_next) ; if (leg->leg_target) *rr = sip_route_dup(home, (sip_route_t *)leg->leg_target); } } else if (leg->leg_target) request_uri = (url_string_t *)leg->leg_target->m_url; if (!request_uri && sip->sip_request) request_uri = (url_string_t *)sip->sip_request->rq_url; to = sip->sip_to ? sip->sip_to : leg->leg_remote; if (!request_uri && to) { if (method != sip_method_register) request_uri = (url_string_t *)to->a_url; else { /* Remove user part from REGISTER requests */ *reg_url = *to->a_url; reg_url->url_user = reg_url->url_password = NULL; request_uri = (url_string_t *)reg_url; } } if (!request_uri) return -1; if (method || method_name) { sip_request_t *rq = sip->sip_request; int use_headers = request_uri == original || (url_t *)request_uri == rq->rq_url; if (!rq || request_uri != (url_string_t *)rq->rq_url || method != rq->rq_method || !su_strmatch(method_name, rq->rq_method_name)) rq = NULL; if (rq == NULL) { rq = sip_request_create(home, method, method_name, request_uri, NULL); if (msg_header_insert(msg, (msg_pub_t *)sip, (msg_header_t *)rq) < 0) return -1; } /* @RFC3261 table 1 (page 152): * Req-URI cannot contain method parameter or headers */ if (rq->rq_url->url_params) { rq->rq_url->url_params = url_strip_param_string((char *)rq->rq_url->url_params, "method"); msg_fragment_clear(rq->rq_common); } if (rq->rq_url->url_headers) { if (use_headers) { char *s = url_query_as_header_string(msg_home(msg), rq->rq_url->url_headers); if (!s) return -1; msg_header_parse_str(msg, (msg_pub_t*)sip, s); } rq->rq_url->url_headers = NULL; msg_fragment_clear(rq->rq_common); } } if (!sip->sip_request) return -1; if (!sip->sip_max_forwards) sip_add_dup(msg, sip, (sip_header_t *)leg->leg_agent->sa_max_forwards); if (!sip->sip_from) sip->sip_from = sip_from_dup(home, leg->leg_local); else if (leg->leg_local && leg->leg_local->a_tag && (!sip->sip_from->a_tag || !su_casematch(sip->sip_from->a_tag, leg->leg_local->a_tag))) sip_from_tag(home, sip->sip_from, leg->leg_local->a_tag); if (sip->sip_from && !sip->sip_from->a_tag) { msg_fragment_clear(sip->sip_from->a_common); sip_from_add_param(home, sip->sip_from, nta_agent_newtag(home, "tag=%s", leg->leg_agent)); } if (sip->sip_to) { if (leg->leg_remote && leg->leg_remote->a_tag) sip_to_tag(home, sip->sip_to, leg->leg_remote->a_tag); } else if (leg->leg_remote) { sip->sip_to = sip_to_dup(home, leg->leg_remote); } else { sip_to_t *to = sip_to_create(home, request_uri); if (to) sip_aor_strip(to->a_url); sip->sip_to = to; } if (!sip->sip_from || !sip->sip_from || !sip->sip_to) return -1; method = sip->sip_request->rq_method; method_name = sip->sip_request->rq_method_name; if (!leg->leg_id && sip->sip_cseq) seq = sip->sip_cseq->cs_seq; else if (method == sip_method_ack || method == sip_method_cancel) /* Dangerous - we may do PRACK/UPDATE meanwhile */ seq = sip->sip_cseq ? sip->sip_cseq->cs_seq : leg->leg_seq; else if (leg->leg_seq) seq = ++leg->leg_seq; else if (sip->sip_cseq) /* Obtain initial value from existing CSeq header */ seq = leg->leg_seq = sip->sip_cseq->cs_seq; else seq = leg->leg_seq = agent_seq(leg->leg_agent); if (!sip->sip_call_id) { if (leg->leg_id) sip->sip_call_id = sip_call_id_dup(home, leg->leg_id); else sip->sip_call_id = sip_call_id_create(home, NULL); } if (!sip->sip_cseq || seq != sip->sip_cseq->cs_seq || method != sip->sip_cseq->cs_method || !su_strmatch(method_name, sip->sip_cseq->cs_method_name)) { sip_cseq_t *cseq = sip_cseq_create(home, seq, method, method_name); if (msg_header_insert(msg, (msg_pub_t *)sip, (msg_header_t *)cseq) < 0) return -1; } return 0; } /* ====================================================================== */ /* 6) Dialogs (legs) */ static void leg_insert(nta_agent_t *agent, nta_leg_t *leg); static int leg_route(nta_leg_t *leg, sip_record_route_t const *route, sip_record_route_t const *reverse, sip_contact_t const *contact, int reroute); static int leg_callback_default(nta_leg_magic_t*, nta_leg_t*, nta_incoming_t*, sip_t const *); #define HTABLE_HASH_LEG(leg) ((leg)->leg_hash) HTABLE_BODIES_WITH(leg_htable, lht, nta_leg_t, HTABLE_HASH_LEG, size_t, hash_value_t); su_inline hash_value_t hash_istring(char const *, char const *, hash_value_t); /**@typedef nta_request_f * * Callback for incoming requests * * This is a callback function invoked by NTA for each incoming SIP request. * * @param lmagic call leg context * @param leg call leg handle * @param ireq incoming request * @param sip incoming request contents * * @retval 100..699 * NTA constructs a reply message with given error code and corresponding * standard phrase, then sends the reply. * * @retval 0 * The application takes care of sending (or not sending) the reply. * * @retval other * All other return values will be interpreted as * @e 500 @e Internal @e server @e error. */ /** * Create a new leg object. * * Creates a leg object, which is used to represent dialogs, partial dialogs * (for example, in case of REGISTER), and destinations within a particular * NTA object. * * When a leg is created, a callback pointer and a application context is * provided. All other parameters are optional. * * @param agent agent object * @param callback function which is called for each * incoming request belonging to this leg * @param magic call leg context * @param tag,value,... optional extra headers in taglist * * When a leg representing dialog is created, the tags SIPTAG_CALL_ID(), * SIPTAG_FROM(), SIPTAG_TO(), and SIPTAG_CSEQ() (for local @CSeq number) are used * to establish dialog context. The SIPTAG_FROM() is used to pass local * address (@From header when making a call, @To header when answering * to a call) to the newly created leg. Respectively, the SIPTAG_TO() is * used to pass remote address (@To header when making a call, @From * header when answering to a call). * * If there is a (preloaded) route associated with the leg, SIPTAG_ROUTE() * and NTATAG_TARGET() can be used. A client or server can also set the * route using @RecordRoute and @Contact headers from a response or * request message with the functions nta_leg_client_route() and * nta_leg_server_route(), respectively. * * When a leg representing a local destination is created, the tags * NTATAG_NO_DIALOG(1), NTATAG_METHOD(), and URLTAG_URL() are used. When a * request with matching request-URI (URLTAG_URL()) and method * (NTATAG_METHOD()) is received, it is passed to the callback function * provided with the leg. * * @sa nta_leg_stateful(), nta_leg_bind(), * nta_leg_tag(), nta_leg_rtag(), * nta_leg_client_route(), nta_leg_server_route(), * nta_leg_destroy(), nta_outgoing_tcreate(), and nta_request_f(). * * @TAGS * NTATAG_NO_DIALOG(), NTATAG_STATELESS(), NTATAG_METHOD(), * URLTAG_URL(), SIPTAG_CALL_ID(), SIPTAG_CALL_ID_STR(), SIPTAG_FROM(), * SIPTAG_FROM_STR(), SIPTAG_TO(), SIPTAG_TO_STR(), SIPTAG_ROUTE(), * NTATAG_TARGET() and SIPTAG_CSEQ(). * */ nta_leg_t *nta_leg_tcreate(nta_agent_t *agent, nta_request_f *callback, nta_leg_magic_t *magic, tag_type_t tag, tag_value_t value, ...) { sip_route_t const *route = NULL; sip_contact_t const *contact = NULL; sip_cseq_t const *cs = NULL; sip_call_id_t const *i = NULL; sip_from_t const *from = NULL; sip_to_t const *to = NULL; char const *method = NULL; char const *i_str = NULL, *to_str = NULL, *from_str = NULL, *cs_str = NULL; url_string_t const *url_string = NULL; int no_dialog = 0; unsigned rseq = 0; /* RFC 3261 section 12.2.1.1 */ uint32_t seq = 0; ta_list ta; nta_leg_t *leg; su_home_t *home; url_t *url; char const *what = NULL; if (agent == NULL) return su_seterrno(EINVAL), NULL; ta_start(ta, tag, value); tl_gets(ta_args(ta), NTATAG_NO_DIALOG_REF(no_dialog), NTATAG_METHOD_REF(method), URLTAG_URL_REF(url_string), SIPTAG_CALL_ID_REF(i), SIPTAG_CALL_ID_STR_REF(i_str), SIPTAG_FROM_REF(from), SIPTAG_FROM_STR_REF(from_str), SIPTAG_TO_REF(to), SIPTAG_TO_STR_REF(to_str), SIPTAG_ROUTE_REF(route), NTATAG_TARGET_REF(contact), NTATAG_REMOTE_CSEQ_REF(rseq), SIPTAG_CSEQ_REF(cs), SIPTAG_CSEQ_STR_REF(cs_str), TAG_END()); ta_end(ta); if (cs) seq = cs->cs_seq; else if (cs_str) seq = strtoul(cs_str, (char **)&cs_str, 10); if (i == NONE) /* Magic value, used for compatibility */ no_dialog = 1; if (!(leg = su_home_clone(agent->sa_home, sizeof(*leg)))) return NULL; home = leg->leg_home; leg->leg_agent = agent; nta_leg_bind(leg, callback, magic); if (from) { /* Now this is kludge */ leg->leg_local_is_to = sip_is_to((sip_header_t*)from); leg->leg_local = sip_to_dup(home, from); } else if (from_str) leg->leg_local = sip_to_make(home, from_str); if (to && no_dialog) { /* Remove tag, if any */ sip_to_t to0[1]; *to0 = *to; to0->a_params = NULL; leg->leg_remote = sip_from_dup(home, to0); } else if (to) leg->leg_remote = sip_from_dup(home, to); else if (to_str) leg->leg_remote = sip_from_make(home, to_str); if (route && route != NONE) leg->leg_route = sip_route_dup(home, route), leg->leg_route_set = 1; if (contact && contact != NONE) { sip_contact_t m[1]; sip_contact_init(m); *m->m_url = *contact->m_url; m->m_url->url_headers = NULL; leg->leg_target = sip_contact_dup(home, m); } url = url_hdup(home, url_string->us_url); /* Match to local hosts */ if (url && agent_aliases(agent, url, NULL)) { url_t *changed = url_hdup(home, url); su_free(home, url); url = changed; } leg->leg_rseq = rseq; leg->leg_seq = seq; leg->leg_url = url; if (from && from != NONE && leg->leg_local == NULL) { what = "cannot duplicate local address"; goto err; } else if (to && to != NONE && leg->leg_remote == NULL) { what = "cannot duplicate remote address"; goto err; } else if (route && route != NONE && leg->leg_route == NULL) { what = "cannot duplicate route"; goto err; } else if (contact && contact != NONE && leg->leg_target == NULL) { what = "cannot duplicate target"; goto err; } else if (url_string && leg->leg_url == NULL) { what = "cannot duplicate local destination"; goto err; } if (!no_dialog) { if (!leg->leg_local || !leg->leg_remote) { /* To and/or From header missing */ if (leg->leg_remote) what = "Missing local dialog address"; else if (leg->leg_local) what = "Missing remote dialog address"; else what = "Missing dialog addresses"; goto err; } leg->leg_dialog = 1; if (i != NULL) leg->leg_id = sip_call_id_dup(home, i); else if (i_str != NULL) leg->leg_id = sip_call_id_make(home, i_str); else leg->leg_id = sip_call_id_create(home, NULL); if (!leg->leg_id) { what = "cannot create Call-ID"; goto err; } leg->leg_hash = leg->leg_id->i_hash; } else if (url) { /* This is "default leg" with a destination URL. */ hash_value_t hash = 0; if (method) { leg->leg_method = su_strdup(home, method); } #if 0 else if (url->url_params) { int len = url_param(url->url_params, "method", NULL, 0); if (len) { char *tmp = su_alloc(home, len); leg->leg_method = tmp; url_param(url->url_params, "method", tmp, len); } } #endif if (url->url_user && strcmp(url->url_user, "") == 0) url->url_user = "%"; /* Match to any user */ hash = hash_istring(url->url_scheme, ":", 0); hash = hash_istring(url->url_host, "", hash); hash = hash_istring(url->url_user, "@", hash); leg->leg_hash = hash; } else { /* This is "default leg" without a destination URL. */ if (agent->sa_default_leg) { SU_DEBUG_1(("%s(): %s\n", "nta_leg_tcreate", "tried to create second default leg")); su_seterrno(EEXIST); goto err; } else { agent->sa_default_leg = leg; } return leg; } if (url) { /* Parameters are ignored when comparing incoming URLs */ url->url_params = NULL; } leg_insert(agent, leg); SU_DEBUG_9(("%s(%p)\n", "nta_leg_tcreate", (void *)leg)); return leg; err: if (what) SU_DEBUG_9(("%s(): %s\n", "nta_leg_tcreate", what)); su_home_zap(leg->leg_home); return NULL; } /** Return the default leg, if any */ nta_leg_t *nta_default_leg(nta_agent_t const *agent) { return agent ? agent->sa_default_leg : NULL; } /** * Insert a call leg to agent. */ static void leg_insert(nta_agent_t *sa, nta_leg_t *leg) { leg_htable_t *leg_hash; assert(leg); assert(sa); if (leg->leg_dialog) leg_hash = sa->sa_dialogs; else leg_hash = sa->sa_defaults; if (leg_htable_is_full(leg_hash)) { leg_htable_resize(sa->sa_home, leg_hash, 0); assert(leg_hash->lht_table); SU_DEBUG_7(("nta: resized%s leg hash to "MOD_ZU"\n", leg->leg_dialog ? "" : " default", leg_hash->lht_size)); } /* Insert entry into hash table (before other legs with same hash) */ leg_htable_insert(leg_hash, leg); } /** * Destroy a leg. * * @param leg leg to be destroyed */ void nta_leg_destroy(nta_leg_t *leg) { SU_DEBUG_9(("nta_leg_destroy(%p)\n", (void *)leg)); if (leg) { leg_htable_t *leg_hash; nta_agent_t *sa = leg->leg_agent; assert(sa); if (leg->leg_dialog) { assert(sa->sa_dialogs); leg_hash = sa->sa_dialogs; } else if (leg != sa->sa_default_leg) { assert(sa->sa_defaults); leg_hash = sa->sa_defaults; } else { sa->sa_default_leg = NULL; leg_hash = NULL; } if (leg_hash) leg_htable_remove(leg_hash, leg); leg_free(sa, leg); } } static void leg_free(nta_agent_t *sa, nta_leg_t *leg) { su_free(sa->sa_home, leg); } /** Return application context for the leg */ nta_leg_magic_t *nta_leg_magic(nta_leg_t const *leg, nta_request_f *callback) { if (leg) if (!callback || leg->leg_callback == callback) return leg->leg_magic; return NULL; } /**Bind a callback function and context to a leg object. * * Change the callback function and context pointer attached to a leg * object. * * @param leg leg object to be bound * @param callback new callback function (or NULL if no callback is desired) * @param magic new context pointer */ void nta_leg_bind(nta_leg_t *leg, nta_request_f *callback, nta_leg_magic_t *magic) { if (leg) { if (callback) leg->leg_callback = callback; else leg->leg_callback = leg_callback_default; leg->leg_magic = magic; } } /** Add a local tag to the leg. * * @param leg leg to be tagged * @param tag tag to be added (if NULL, a tag generated by @b NTA is added) * * @return * Pointer to tag if successful, NULL otherwise. */ char const *nta_leg_tag(nta_leg_t *leg, char const *tag) { if (!leg || !leg->leg_local) return su_seterrno(EINVAL), NULL; if (tag && strchr(tag, '=')) tag = strchr(tag, '=') + 1; /* If there already is a tag, return NULL if it does not match with new one */ if (leg->leg_local->a_tag) { if (tag == NULL || su_casematch(tag, leg->leg_local->a_tag)) return leg->leg_local->a_tag; else return NULL; } if (tag) { if (sip_to_tag(leg->leg_home, leg->leg_local, tag) < 0) return NULL; leg->leg_tagged = 1; return leg->leg_local->a_tag; } tag = nta_agent_newtag(leg->leg_home, "tag=%s", leg->leg_agent); if (!tag || sip_to_add_param(leg->leg_home, leg->leg_local, tag) < 0) return NULL; leg->leg_tagged = 1; return leg->leg_local->a_tag; } /** Get Call-Id. * * @param leg pointer to dialog object * * @return Pointer to Call-Id structure, or NULL if there is none. */ sip_call_id_t const * nta_leg_get_call_id(nta_leg_t const *leg) { if (leg) return leg->leg_id; else return NULL; } /** Get local tag. */ char const *nta_leg_get_tag(nta_leg_t const *leg) { if (leg && leg->leg_local) return leg->leg_local->a_tag; else return NULL; } /** Add a remote tag to the leg. * * @note No remote tag is ever generated. * * @param leg leg to be tagged * @param tag tag to be added (@b must be non-NULL) * * @return * Pointer to tag if successful, NULL otherwise. */ char const *nta_leg_rtag(nta_leg_t *leg, char const *tag) { /* Add a tag parameter, unless there already is a tag */ if (leg && leg->leg_remote && tag) { if (sip_from_tag(leg->leg_home, leg->leg_remote, tag) < 0) return NULL; } if (leg && leg->leg_remote) return leg->leg_remote->a_tag; else return NULL; } /** Get remote tag. */ char const *nta_leg_get_rtag(nta_leg_t const *leg) { if (leg && leg->leg_remote) return leg->leg_remote->a_tag; else return NULL; } /** Get local request sequence number. */ uint32_t nta_leg_get_seq(nta_leg_t const *leg) { return leg ? leg->leg_seq : 0; } /** Get remote request sequence number. */ uint32_t nta_leg_get_rseq(nta_leg_t const *leg) { return leg ? leg->leg_rseq : 0; } /** Save target and route set at UAC side. * * @sa nta_leg_client_reroute(), nta_leg_server_route(), @RFC3261 section 12.1.2 * * @bug Allows modifying the route set after initial transaction, if initial * transaction had no @RecordRoute headers. * * @deprecated Use nta_leg_client_reroute() instead. */ int nta_leg_client_route(nta_leg_t *leg, sip_record_route_t const *route, sip_contact_t const *contact) { return leg_route(leg, NULL, route, contact, 0); } /** Save target and route set at UAC side. * * If @a initial is true, the route set is modified even if it has been set * earlier. * * @param leg pointer to dialog leg * @param route @RecordRoute headers from response * @param contact @Contact header from response * @param initial true if response to initial transaction * * @sa nta_leg_client_route(), nta_leg_server_route(), @RFC3261 section 12.1.2 * * @NEW_1_12_11 */ int nta_leg_client_reroute(nta_leg_t *leg, sip_record_route_t const *route, sip_contact_t const *contact, int initial) { return leg_route(leg, NULL, route, contact, initial ? 2 : 1); } /** Save target and route set at UAS side. * * @param leg pointer to dialog leg * @param route @RecordRoute headers from request * @param contact @Contact header from request * * @sa nta_leg_client_reroute(), @RFC3261 section 12.1.1 */ int nta_leg_server_route(nta_leg_t *leg, sip_record_route_t const *route, sip_contact_t const *contact) { return leg_route(leg, route, NULL, contact, 1); } /** Return route components. */ int nta_leg_get_route(nta_leg_t *leg, sip_route_t const **return_route, sip_contact_t const **return_target) { if (!leg) return -1; if (return_route) *return_route = leg->leg_route; if (return_target) *return_target = leg->leg_target; return 0; } /** Generate @Replaces header. * * @since New in @VERSION_1_12_2. */ sip_replaces_t * nta_leg_make_replaces(nta_leg_t *leg, su_home_t *home, int early_only) { char const *from_tag, *to_tag; if (!leg) return NULL; if (!leg->leg_dialog || !leg->leg_local || !leg->leg_remote || !leg->leg_id) return NULL; from_tag = leg->leg_local->a_tag; if (!from_tag) from_tag = "0"; to_tag = leg->leg_remote->a_tag; if (!to_tag) to_tag = "0"; return sip_replaces_format(home, "%s;from-tag=%s;to-tag=%s%s", leg->leg_id->i_id, from_tag, to_tag, early_only ? ";early-only" : ""); } /** Get dialog leg by @Replaces header. * * @since New in @VERSION_1_12_2. */ nta_leg_t * nta_leg_by_replaces(nta_agent_t *sa, sip_replaces_t const *rp) { nta_leg_t *leg = NULL; if (sa && rp && rp->rp_call_id && rp->rp_from_tag && rp->rp_to_tag) { char const *from_tag = rp->rp_from_tag, *to_tag = rp->rp_to_tag; sip_call_id_t id[1]; sip_call_id_init(id); id->i_hash = msg_hash_string(id->i_id = rp->rp_call_id); leg = leg_find(sa, NULL, NULL, id, from_tag, to_tag); if (leg == NULL && strcmp(from_tag, "0") == 0) leg = leg_find(sa, NULL, NULL, id, NULL, to_tag); if (leg == NULL && strcmp(to_tag, "0") == 0) leg = leg_find(sa, NULL, NULL, id, from_tag, NULL); } return leg; } /**@internal * Find a leg corresponding to the request message. * */ static nta_leg_t * leg_find_call_id(nta_agent_t const *sa, sip_call_id_t const *i) { hash_value_t hash = i->i_hash; leg_htable_t const *lht = sa->sa_dialogs; nta_leg_t **ll, *leg = NULL; for (ll = leg_htable_hash(lht, hash); (leg = *ll); ll = leg_htable_next(lht, ll)) { sip_call_id_t const *leg_i = leg->leg_id; if (leg->leg_hash != hash) continue; if (strcmp(leg_i->i_id, i->i_id) != 0) continue; return leg; } return leg; } /** Get dialog leg by @CallID. * * @note Usually there should be only single dialog per @CallID on * User-Agents. However, proxies may fork requests initiating the dialog and * result in multiple calls per @CallID. * * @since New in @VERSION_1_12_9. */ nta_leg_t * nta_leg_by_call_id(nta_agent_t *sa, const char *call_id) { nta_leg_t *leg = NULL; if (call_id) { sip_call_id_t id[1]; sip_call_id_init(id); id->i_hash = msg_hash_string(id->i_id = call_id); leg = leg_find_call_id(sa, id); } return leg; } /** Calculate a simple case-insensitive hash over a string */ su_inline hash_value_t hash_istring(char const *s, char const *term, hash_value_t hash) { if (s) { for (; *s; s++) { unsigned char c = *s; if ('A' <= c && c <= 'Z') c += 'a' - 'A'; hash = 38501U * (hash + c); } for (s = term; *s; s++) { unsigned char c = *s; hash = 38501U * (hash + c); } } return hash; } /** @internal Handle requests intended for this leg. */ static void leg_recv(nta_leg_t *leg, msg_t *msg, sip_t *sip, tport_t *tport) { nta_agent_t *agent = leg->leg_agent; nta_incoming_t *irq; sip_method_t method = sip->sip_request->rq_method; char const *method_name = sip->sip_request->rq_method_name; char const *tag = NULL; int status; if (leg->leg_local) tag = leg->leg_local->a_tag; if (leg->leg_dialog) agent->sa_stats->as_dialog_tr++; /* RFC-3262 section 3 (page 4) */ if (agent->sa_is_a_uas && method == sip_method_prack) { mreply(agent, NULL, 481, "No such response", msg, tport, 0, 0, NULL, TAG_END()); return; } if (!(irq = incoming_create(agent, msg, sip, tport, tag))) { SU_DEBUG_3(("nta: leg_recv(%p): cannot create transaction for %s\n", (void *)leg, method_name)); mreply(agent, NULL, SIP_500_INTERNAL_SERVER_ERROR, msg, tport, 0, 0, NULL, TAG_END()); return; } irq->irq_in_callback = 1; status = incoming_callback(leg, irq, sip); irq->irq_in_callback = 0; if (irq->irq_destroyed) { if (irq->irq_terminated) { incoming_free(irq); return; } if (status < 200) status = 500; } if (status == 0) return; if (status < 100 || status > 699) { SU_DEBUG_3(("nta_leg(%p): invalid status %03d from callback\n", (void *)leg, status)); status = 500; } else if (method == sip_method_invite && status >= 200 && status < 300) { SU_DEBUG_3(("nta_leg(%p): invalid INVITE status %03d from callback\n", (void *)leg, status)); status = 500; } if (status >= 100 && irq->irq_status < 200) nta_incoming_treply(irq, status, NULL, TAG_END()); if (status >= 200) nta_incoming_destroy(irq); } /**Compare two SIP from/to fields. * * @retval nonzero if matching. * @retval zero if not matching. */ su_inline int addr_cmp(url_t const *a, url_t const *b) { if (b == NULL) return 0; else return host_cmp(a->url_host, b->url_host) || su_strcmp(a->url_port, b->url_port) || su_strcmp(a->url_user, b->url_user); } /** Get a leg by dialog. * * Search for a dialog leg from agent's hash table. The matching rules based * on parameters are as follows: * * @param agent pointer to agent object * @param request_uri if non-NULL, and there is destination URI * associated with the dialog, these URIs must match * @param call_id if non-NULL, must match with @CallID header contents * @param remote_tag if there is remote tag * associated with dialog, @a remote_tag must match * @param remote_uri ignored * @param local_tag if non-NULL and there is local tag associated with leg, * it must math * @param local_uri ignored * * @note * If @a remote_tag or @a local_tag is an empty string (""), the tag is * ignored when matching legs. */ nta_leg_t *nta_leg_by_dialog(nta_agent_t const *agent, url_t const *request_uri, sip_call_id_t const *call_id, char const *remote_tag, url_t const *remote_uri, char const *local_tag, url_t const *local_uri) { void *to_be_freed = NULL; url_t *url; url_t url0[1]; nta_leg_t *leg; if (!agent || !call_id) return su_seterrno(EINVAL), NULL; if (request_uri == NULL) { url = NULL; } else if (URL_IS_STRING(request_uri)) { /* accept a string as URL */ to_be_freed = url = url_hdup(NULL, request_uri); } else { *url0 = *request_uri, url = url0; } if (url) { url->url_params = NULL; agent_aliases(agent, url, NULL); /* canonize url */ } if (remote_tag && remote_tag[0] == '\0') remote_tag = NULL; if (local_tag && local_tag[0] == '\0') local_tag = NULL; leg = leg_find(agent, NULL, url, call_id, remote_tag, local_tag); if (to_be_freed) su_free(NULL, to_be_freed); return leg; } /**@internal * Find a leg corresponding to the request message. * * A leg matches to message if leg_match_request() returns true ("Call-ID", * "To"-tag, and "From"-tag match). */ static nta_leg_t *leg_find(nta_agent_t const *sa, char const *method_name, url_t const *request_uri, sip_call_id_t const *i, char const *from_tag, char const *to_tag) { hash_value_t hash = i->i_hash; leg_htable_t const *lht = sa->sa_dialogs; nta_leg_t **ll, *leg, *loose_match = NULL; for (ll = leg_htable_hash(lht, hash); (leg = *ll); ll = leg_htable_next(lht, ll)) { sip_call_id_t const *leg_i = leg->leg_id; char const *remote_tag = leg->leg_remote->a_tag; char const *local_tag = leg->leg_local->a_tag; url_t const *leg_url = leg->leg_url; char const *leg_method = leg->leg_method; if (leg->leg_hash != hash) continue; if (strcmp(leg_i->i_id, i->i_id) != 0) continue; /* Do not match if the incoming To has tag, but the local does not */ if (!local_tag && to_tag) continue; /* * Do not match if incoming To has no tag and we have local tag * and the tag has been there from the beginning. */ if (local_tag && !to_tag && !leg->leg_tagged) continue; /* Do not match if incoming From has no tag but remote has a tag */ if (remote_tag && !from_tag) continue; /* Avoid matching with itself */ if (!remote_tag != !from_tag && !local_tag != !to_tag) continue; if (local_tag && to_tag && !su_casematch(local_tag, to_tag) && to_tag[0]) continue; if (remote_tag && from_tag && !su_casematch(remote_tag, from_tag) && from_tag[0]) continue; if (leg_url && request_uri && url_cmp(leg_url, request_uri)) continue; if (leg_method && method_name && !su_casematch(method_name, leg_method)) continue; /* Perfect match if both local and To have tag * or local does not have tag. */ if ((!local_tag || to_tag)) return leg; if (loose_match == NULL) loose_match = leg; } return loose_match; } /** Get leg by destination */ nta_leg_t *nta_leg_by_uri(nta_agent_t const *agent, url_string_t const *us) { url_t *url; nta_leg_t *leg = NULL; if (!agent) return NULL; if (!us) return agent->sa_default_leg; url = url_hdup(NULL, us->us_url); if (url) { agent_aliases(agent, url, NULL); leg = dst_find(agent, url, NULL); su_free(NULL, url); } return leg; } /** Find a non-dialog leg corresponding to the request uri u0 */ static nta_leg_t *dst_find(nta_agent_t const *sa, url_t const *u0, char const *method_name) { hash_value_t hash, hash2; leg_htable_t const *lht = sa->sa_defaults; nta_leg_t **ll, *leg, *loose_match = NULL; int again; url_t url[1]; *url = *u0; hash = hash_istring(url->url_scheme, ":", 0); hash = hash_istring(url->url_host, "", hash); hash2 = hash_istring("%", "@", hash); hash = hash_istring(url->url_user, "@", hash); /* First round, search with user name */ /* Second round, search without user name */ do { for (ll = leg_htable_hash(lht, hash); (leg = *ll); ll = leg_htable_next(lht, ll)) { if (leg->leg_hash != hash) continue; if (url_cmp(url, leg->leg_url)) continue; if (!method_name) { if (leg->leg_method) continue; return leg; } else if (leg->leg_method) { if (!su_casematch(method_name, leg->leg_method)) continue; return leg; } loose_match = leg; } if (loose_match) return loose_match; again = 0; if (url->url_user && strcmp(url->url_user, "%")) { url->url_user = "%"; hash = hash2; again = 1; } } while (again); return NULL; } /** Set leg route and target URL. * * Sets the leg route and contact using the @RecordRoute and @Contact * headers. * * @param reroute - allow rerouting * - if 1, follow @RFC3261 semantics * - if 2, response to initial transaction) */ static int leg_route(nta_leg_t *leg, sip_record_route_t const *route, sip_record_route_t const *reverse, sip_contact_t const *contact, int reroute) { su_home_t *home = leg->leg_home; sip_route_t *r, r0[1], *old; int route_is_set; if (!leg) return -1; if (route == NULL && reverse == NULL && contact == NULL) return 0; sip_route_init(r0); route_is_set = reroute ? leg->leg_route_set : leg->leg_route != NULL; if (route_is_set && reroute <= 1) { r = leg->leg_route; } else if (route) { r = sip_route_fixdup(home, route); if (!r) return -1; } else if (reverse) { r = sip_route_reverse(home, reverse); if (!r) return -1; } else r = NULL; #ifdef NTA_STRICT_ROUTING /* * Handle Contact according to the RFC2543bis04 sections 16.1, 16.2 and 16.4. */ if (contact) { *r0->r_url = *contact->m_url; if (!(m_r = sip_route_dup(leg->leg_home, r0))) return -1; /* Append, but replace last entry if it was generated from contact */ for (rr = &r; *rr; rr = &(*rr)->r_next) if (leg->leg_contact_set && (*rr)->r_next == NULL) break; } else rr = NULL; if (rr) { if (*rr) su_free(leg->leg_home, *rr); *rr = m_r; } if (m_r != NULL) leg->leg_contact_set = 1; #else if (r && r->r_url->url_params) leg->leg_loose_route = url_has_param(r->r_url, "lr"); if (contact) { sip_contact_t *target, m[1], *m0; sip_contact_init(m); *m->m_url = *contact->m_url; m->m_url->url_headers = NULL; target = sip_contact_dup(leg->leg_home, m); if (target && target->m_url->url_params) { /* Remove ttl, method. @RFC3261 table 1, page 152 */ char *p = (char *)target->m_url->url_params; p = url_strip_param_string(p, "method"); p = url_strip_param_string(p, "ttl"); target->m_url->url_params = p; } m0 = leg->leg_target, leg->leg_target = target; if (m0) su_free(leg->leg_home, m0); } #endif old = leg->leg_route; leg->leg_route = r; if (old && old != r) msg_header_free(leg->leg_home, (msg_header_t *)old); leg->leg_route_set = 1; return 0; } /** @internal Default leg callback. */ static int leg_callback_default(nta_leg_magic_t *magic, nta_leg_t *leg, nta_incoming_t *irq, sip_t const *sip) { nta_incoming_treply(irq, SIP_501_NOT_IMPLEMENTED, TAG_END()); return 501; } /* ====================================================================== */ /* 7) Server-side (incoming) transactions */ #define HTABLE_HASH_IRQ(irq) ((irq)->irq_hash) HTABLE_BODIES_WITH(incoming_htable, iht, nta_incoming_t, HTABLE_HASH_IRQ, size_t, hash_value_t); static void incoming_insert(nta_agent_t *agent, incoming_queue_t *queue, nta_incoming_t *irq); su_inline int incoming_is_queued(nta_incoming_t const *irq); su_inline void incoming_queue(incoming_queue_t *queue, nta_incoming_t *); su_inline void incoming_remove(nta_incoming_t *irq); su_inline void incoming_set_timer(nta_incoming_t *, uint32_t interval); su_inline void incoming_reset_timer(nta_incoming_t *); su_inline size_t incoming_mass_destroy(nta_agent_t *, incoming_queue_t *); static int incoming_set_params(nta_incoming_t *irq, tagi_t const *tags); su_inline int incoming_set_compartment(nta_incoming_t *irq, tport_t *tport, msg_t *msg, int create_if_needed); su_inline nta_incoming_t *incoming_call_callback(nta_incoming_t *, msg_t *, sip_t *); su_inline int incoming_final_failed(nta_incoming_t *irq, msg_t *); static void incoming_retransmit_reply(nta_incoming_t *irq, tport_t *tport); /** Create a default server transaction. * * The default server transaction is used by a proxy to forward responses * statelessly. * * @param agent pointer to agent object * * @retval pointer to default server transaction object * @retval NULL if failed */ nta_incoming_t *nta_incoming_default(nta_agent_t *agent) { msg_t *msg; su_home_t *home; nta_incoming_t *irq; if (agent == NULL) return su_seterrno(EFAULT), NULL; if (agent->sa_default_incoming) return su_seterrno(EEXIST), NULL; msg = nta_msg_create(agent, 0); if (!msg) return NULL; irq = su_zalloc(home = msg_home(msg), sizeof(*irq)); if (!irq) return (void)msg_destroy(msg), NULL; irq->irq_home = home; irq->irq_request = NULL; irq->irq_agent = agent; irq->irq_received = agent_now(agent); irq->irq_method = sip_method_invalid; irq->irq_default = 1; agent->sa_default_incoming = irq; return irq; } /** Create a server transaction. * * Create a server transaction for a request message. This function is used * when an element processing requests statelessly wants to process a * particular request statefully. * * @param agent pointer to agent object * @param leg pointer to leg object (either @a agent or @a leg may be NULL) * @param msg pointer to message object * @param sip pointer to SIP structure (may be NULL) * @param tag,value,... optional tagged parameters * * @note * The ownership of @a msg is taken over by the function even if the * function fails. * * @TAGS * @TAG NTATAG_TPORT() specifies the transport used to receive the request * and also default transport for sending the response. * * @retval nta_incoming_t pointer to the newly created server transaction * @retval NULL if failed */ nta_incoming_t *nta_incoming_create(nta_agent_t *agent, nta_leg_t *leg, msg_t *msg, sip_t *sip, tag_type_t tag, tag_value_t value, ...) { char const *to_tag = NULL; tport_t *tport = NULL; ta_list ta; nta_incoming_t *irq; if (msg == NULL) return NULL; if (agent == NULL && leg != NULL) agent = leg->leg_agent; if (sip == NULL) sip = sip_object(msg); if (agent == NULL || sip == NULL || !sip->sip_request || !sip->sip_cseq) return msg_destroy(msg), NULL; ta_start(ta, tag, value); tl_gets(ta_args(ta), NTATAG_TPORT_REF(tport), TAG_END()); ta_end(ta); if (leg && leg->leg_local) to_tag = leg->leg_local->a_tag; if (tport == NULL) tport = tport_delivered_by(agent->sa_tports, msg); irq = incoming_create(agent, msg, sip, tport, to_tag); if (!irq) msg_destroy(msg); return irq; } /** @internal Create a new incoming transaction object. */ static nta_incoming_t *incoming_create(nta_agent_t *agent, msg_t *msg, sip_t *sip, tport_t *tport, char const *tag) { nta_incoming_t *irq = su_zalloc(msg_home(msg), sizeof(*irq)); agent->sa_stats->as_server_tr++; if (irq) { su_home_t *home; incoming_queue_t *queue; sip_method_t method = sip->sip_request->rq_method; irq->irq_request = msg; irq->irq_home = home = msg_home(msg_ref(msg)); irq->irq_agent = agent; irq->irq_received = agent_now(agent); /* Timestamp originally from tport */ irq->irq_method = method; irq->irq_rq = sip_request_copy(home, sip->sip_request); irq->irq_from = sip_from_copy(home, sip->sip_from); irq->irq_to = sip_to_copy(home, sip->sip_to); irq->irq_call_id = sip_call_id_copy(home, sip->sip_call_id); irq->irq_cseq = sip_cseq_copy(home, sip->sip_cseq); irq->irq_via = sip_via_copy(home, sip->sip_via); switch (method) { case sip_method_ack: case sip_method_cancel: case sip_method_bye: case sip_method_options: case sip_method_register: /* Handling Path is up to application */ case sip_method_info: case sip_method_prack: case sip_method_publish: break; default: irq->irq_record_route = sip_record_route_copy(home, sip->sip_record_route); } irq->irq_branch = sip->sip_via->v_branch; irq->irq_reliable_tp = tport_is_reliable(tport); irq->irq_extra_100 = 1; /* Sending extra 100 trying true by default */ if (sip->sip_timestamp) irq->irq_timestamp = sip_timestamp_copy(home, sip->sip_timestamp); /* Tag transaction */ if (tag) sip_to_tag(home, irq->irq_to, tag); irq->irq_tag = irq->irq_to->a_tag; if (method != sip_method_ack) { int *use_rport = NULL; int retry_without_rport = 0; if (agent->sa_server_rport) use_rport = &retry_without_rport, retry_without_rport = 1; if (nta_tpn_by_via(irq->irq_tpn, irq->irq_via, use_rport) < 0) SU_DEBUG_1(("%s: bad via\n", __func__)); } incoming_set_compartment(irq, tport, msg, 0); if (method == sip_method_invite) { irq->irq_must_100rel = sip->sip_require && sip_has_feature(sip->sip_require, "100rel"); if (irq->irq_must_100rel || (sip->sip_supported && sip_has_feature(sip->sip_supported, "100rel"))) { irq->irq_rseq = su_randint(1, 0x7fffffff); /* Initialize rseq */ } queue = agent->sa_in.proceeding; if (irq->irq_reliable_tp) incoming_set_timer(irq, agent->sa_t2 / 2); /* N1 = T2 / 2 */ else incoming_set_timer(irq, 200); /* N1 = 200 ms */ irq->irq_tport = tport_ref(tport); } else if (method == sip_method_ack) { irq->irq_status = 700; /* Never send reply to ACK */ irq->irq_completed = 1; if (irq->irq_reliable_tp || !agent->sa_is_a_uas) { queue = agent->sa_in.terminated; irq->irq_terminated = 1; } else { queue = agent->sa_in.completed; /* Timer J */ } } else { queue = agent->sa_in.proceeding; /* RFC 4320 (nit-actions-03): Blacklisting on a late response occurs even over reliable transports. Thus, if an element processing a request received over a reliable transport is delaying its final response at all, sending a 100 Trying well in advance of the timeout will prevent blacklisting. Sending a 100 Trying immediately will not harm the transaction as it would over UDP, but a policy of always sending such a message results in unneccessary traffic. A policy of sending a 100 Trying after the period of time in which Timer E reaches T2 had this been a UDP hop is one reasonable compromise. */ if (agent->sa_extra_100 && irq->irq_reliable_tp) incoming_set_timer(irq, agent->sa_t2 / 2); /* T2 / 2 */ irq->irq_tport = tport_ref(tport); } irq->irq_hash = NTA_HASH(irq->irq_call_id, irq->irq_cseq->cs_seq); incoming_insert(agent, queue, irq); } return irq; } /** @internal * Insert incoming transaction to hash table. */ static void incoming_insert(nta_agent_t *agent, incoming_queue_t *queue, nta_incoming_t *irq) { incoming_queue(queue, irq); if (incoming_htable_is_full(agent->sa_incoming)) incoming_htable_resize(agent->sa_home, agent->sa_incoming, 0); if (irq->irq_method != sip_method_ack) incoming_htable_insert(agent->sa_incoming, irq); else /* ACK is appended - final response with tags match with it, * not with the original INVITE transaction */ /* XXX - what about rfc2543 servers, which do not add tag? */ incoming_htable_append(agent->sa_incoming, irq); } /** Call callback for incoming request */ static int incoming_callback(nta_leg_t *leg, nta_incoming_t *irq, sip_t *sip) { sip_method_t method = sip->sip_request->rq_method; char const *method_name = sip->sip_request->rq_method_name; /* RFC-3261 section 12.2.2 (page 76) */ if (leg->leg_dialog && irq->irq_agent->sa_is_a_uas && method != sip_method_ack) { uint32_t seq = sip->sip_cseq->cs_seq; if (leg->leg_rseq > sip->sip_cseq->cs_seq) { SU_DEBUG_3(("nta_leg(%p): out-of-order %s (%u < %u)\n", (void *)leg, method_name, seq, leg->leg_rseq)); return 500; } leg->leg_rseq = seq; } return leg->leg_callback(leg->leg_magic, leg, irq, sip); } /** * Destroy an incoming transaction. * * This function does not actually free transaction object, but marks it as * disposable. The object is freed after a timeout. * * @param irq incoming request object to be destroyed */ void nta_incoming_destroy(nta_incoming_t *irq) { if (irq) { irq->irq_callback = NULL; irq->irq_magic = NULL; irq->irq_destroyed = 1; if (!irq->irq_in_callback) { if (irq->irq_terminated || irq->irq_default) incoming_free(irq); else if (irq->irq_status < 200) nta_incoming_treply(irq, SIP_500_INTERNAL_SERVER_ERROR, TAG_END()); } } } /** @internal * Initialize a queue for incoming transactions. */ static void incoming_queue_init(incoming_queue_t *queue, unsigned timeout) { memset(queue, 0, sizeof *queue); queue->q_tail = &queue->q_head; queue->q_timeout = timeout; } /** Change the timeout value of a queue */ static void incoming_queue_adjust(nta_agent_t *sa, incoming_queue_t *queue, uint32_t timeout) { nta_incoming_t *irq; uint32_t latest; if (timeout >= queue->q_timeout || !queue->q_head) { queue->q_timeout = timeout; return; } latest = set_timeout(sa, queue->q_timeout = timeout); for (irq = queue->q_head; irq; irq = irq->irq_next) { if ((int32_t)(irq->irq_timeout - latest) > 0) irq->irq_timeout = latest; } } /** @internal * Test if an incoming transaction is in a queue. */ su_inline int incoming_is_queued(nta_incoming_t const *irq) { return irq && irq->irq_queue; } /** @internal * Insert an incoming transaction into a queue. * * Insert a server transaction into a queue, and sets the corresponding * timeout at the same time. */ su_inline void incoming_queue(incoming_queue_t *queue, nta_incoming_t *irq) { if (irq->irq_queue == queue) { assert(queue->q_timeout == 0); return; } if (incoming_is_queued(irq)) incoming_remove(irq); assert(*queue->q_tail == NULL); irq->irq_timeout = set_timeout(irq->irq_agent, queue->q_timeout); irq->irq_queue = queue; irq->irq_prev = queue->q_tail; *queue->q_tail = irq; queue->q_tail = &irq->irq_next; queue->q_length++; } /** @internal * Remove an incoming transaction from a queue. */ su_inline void incoming_remove(nta_incoming_t *irq) { assert(incoming_is_queued(irq)); assert(irq->irq_queue->q_length > 0); if ((*irq->irq_prev = irq->irq_next)) irq->irq_next->irq_prev = irq->irq_prev; else irq->irq_queue->q_tail = irq->irq_prev, assert(!*irq->irq_queue->q_tail); irq->irq_queue->q_length--; irq->irq_next = NULL; irq->irq_prev = NULL; irq->irq_queue = NULL; irq->irq_timeout = 0; } su_inline void incoming_set_timer(nta_incoming_t *irq, uint32_t interval) { nta_incoming_t **rq; assert(irq); if (interval == 0) { incoming_reset_timer(irq); return; } if (irq->irq_rprev) { if ((*irq->irq_rprev = irq->irq_rnext)) irq->irq_rnext->irq_rprev = irq->irq_rprev; if (irq->irq_agent->sa_in.re_t1 == &irq->irq_rnext) irq->irq_agent->sa_in.re_t1 = irq->irq_rprev; } else { irq->irq_agent->sa_in.re_length++; } irq->irq_retry = set_timeout(irq->irq_agent, irq->irq_interval = interval); rq = irq->irq_agent->sa_in.re_t1; if (!(*rq) || (int32_t)((*rq)->irq_retry - irq->irq_retry) > 0) rq = &irq->irq_agent->sa_in.re_list; while (*rq && (int32_t)((*rq)->irq_retry - irq->irq_retry) <= 0) rq = &(*rq)->irq_rnext; if ((irq->irq_rnext = *rq)) irq->irq_rnext->irq_rprev = &irq->irq_rnext; *rq = irq; irq->irq_rprev = rq; /* Optimization: keep special place for transactions with T1 interval */ if (interval == irq->irq_agent->sa_t1) irq->irq_agent->sa_in.re_t1 = rq; } su_inline void incoming_reset_timer(nta_incoming_t *irq) { if (irq->irq_rprev) { if ((*irq->irq_rprev = irq->irq_rnext)) irq->irq_rnext->irq_rprev = irq->irq_rprev; if (irq->irq_agent->sa_in.re_t1 == &irq->irq_rnext) irq->irq_agent->sa_in.re_t1 = irq->irq_rprev; irq->irq_agent->sa_in.re_length--; } irq->irq_interval = 0, irq->irq_retry = 0; irq->irq_rnext = NULL, irq->irq_rprev = NULL; } /** @internal * Free an incoming transaction. */ static void incoming_free(nta_incoming_t *irq) { SU_DEBUG_9(("nta: incoming_free(%p)\n", (void *)irq)); incoming_cut_off(irq); incoming_reclaim(irq); } /** Remove references to the irq */ su_inline void incoming_cut_off(nta_incoming_t *irq) { nta_agent_t *agent = irq->irq_agent; assert(agent); if (irq->irq_default) { if (irq == agent->sa_default_incoming) agent->sa_default_incoming = NULL; irq->irq_default = 0; return; } if (incoming_is_queued(irq)) incoming_remove(irq); incoming_reset_timer(irq); incoming_htable_remove(agent->sa_incoming, irq); if (irq->irq_cc) nta_compartment_decref(&irq->irq_cc); if (irq->irq_tport) tport_decref(&irq->irq_tport); } /** Reclaim the memory used by irq */ su_inline void incoming_reclaim(nta_incoming_t *irq) { su_home_t *home = irq->irq_home; nta_reliable_t *rel, *rel_next; if (irq->irq_request) msg_destroy(irq->irq_request), irq->irq_request = NULL; if (irq->irq_request2) msg_destroy(irq->irq_request2), irq->irq_request2 = NULL; if (irq->irq_response) msg_destroy(irq->irq_response), irq->irq_response = NULL; for (rel = irq->irq_reliable; rel; rel = rel_next) { rel_next = rel->rel_next; if (rel->rel_unsent) msg_destroy(rel->rel_unsent); su_free(irq->irq_agent->sa_home, rel); } irq->irq_home = NULL; su_free(home, irq); msg_destroy((msg_t *)home); } /** Queue request to be freed */ su_inline void incoming_free_queue(incoming_queue_t *q, nta_incoming_t *irq) { incoming_cut_off(irq); incoming_queue(q, irq); } /** Reclaim memory used by queue of requests */ static void incoming_reclaim_queued(su_root_magic_t *rm, su_msg_r msg, union sm_arg_u *u) { incoming_queue_t *q = u->a_incoming_queue; nta_incoming_t *irq, *irq_next; SU_DEBUG_9(("incoming_reclaim_all(%p, %p, %p)\n", (void *)rm, (void *)msg, (void *)u)); for (irq = q->q_head; irq; irq = irq_next) { irq_next = irq->irq_next; incoming_reclaim(irq); } } /**Bind a callback and context to an incoming transaction object * * Set the callback function and context pointer attached to an incoming * request object. The callback function will be invoked if the incoming * request is cancelled, or if the final response to an incoming @b INVITE * request has been acknowledged. * * If the callback is NULL, or no callback has been bound, NTA invokes the * request callback of the call leg. * * @param irq incoming transaction * @param callback callback function * @param magic application context */ void nta_incoming_bind(nta_incoming_t *irq, nta_ack_cancel_f *callback, nta_incoming_magic_t *magic) { if (irq) { irq->irq_callback = callback; irq->irq_magic = magic; } } /** Add a @To tag to incoming request if needed. * * If @a tag is NULL, a new tag is generated. */ char const *nta_incoming_tag(nta_incoming_t *irq, char const *tag) { if (!irq) return su_seterrno(EFAULT), NULL; if (irq->irq_default) return su_seterrno(EINVAL), NULL; if (tag && strchr(tag, '=')) tag = strchr(tag, '=') + 1; if (tag && irq->irq_tag && !su_casematch(tag, irq->irq_tag)) return NULL; if (!irq->irq_tag) { if (tag) tag = su_strdup(irq->irq_home, tag); else tag = nta_agent_newtag(irq->irq_home, NULL, irq->irq_agent); if (!tag) return tag; irq->irq_tag = tag; irq->irq_tag_set = 1; } return irq->irq_tag; } /**Get request message. * * Retrieve the incoming request message of the incoming transaction. Note * that the message is not copied, but a new reference to it is created. * * @param irq incoming transaction handle * * @retval * A pointer to request message is returned. */ msg_t *nta_incoming_getrequest(nta_incoming_t *irq) { msg_t *msg = NULL; if (irq && !irq->irq_default) msg = msg_ref(irq->irq_request); return msg; } /**Get ACK or CANCEL message. * * Retrieve the incoming ACK or CANCEL request message of the incoming * transaction. Note that the ACK or CANCEL message is not copied, but a new * reference to it is created. * * @param irq incoming transaction handle * * @retval A pointer to request message is returned, or NULL if there is no * CANCEL or ACK received. */ msg_t *nta_incoming_getrequest_ackcancel(nta_incoming_t *irq) { msg_t *msg = NULL; if (irq && irq->irq_request2) msg = msg_ref(irq->irq_request2); return msg; } /**Get response message. * * Retrieve the response message latest sent by the server transaction. Note * that the message is not copied, but a new reference to it is created. Use * msg_dup() or msg_copy() to make a copy of it. * * @param irq incoming transaction handle * * @retval * A pointer to a response message is returned. */ msg_t *nta_incoming_getresponse(nta_incoming_t *irq) { msg_t *msg = NULL; if (irq && irq->irq_response) msg = msg_ref(irq->irq_response); return msg; } /** Get method of a server transaction. */ sip_method_t nta_incoming_method(nta_incoming_t const *irq) { return irq ? irq->irq_method : sip_method_invalid; } /** Get method name of a server transaction. */ char const *nta_incoming_method_name(nta_incoming_t const *irq) { if (irq == NULL) return NULL; else if (irq->irq_rq) return irq->irq_rq->rq_method_name; else return "*"; } /** Get Request-URI of a server transaction */ url_t const *nta_incoming_url(nta_incoming_t const *irq) { return irq && irq->irq_rq ? irq->irq_rq->rq_url : NULL; } /** Get sequence number of a server transaction. */ uint32_t nta_incoming_cseq(nta_incoming_t const *irq) { return irq && irq->irq_cseq ? irq->irq_cseq->cs_seq : 0; } /** Get local tag for incoming request */ char const *nta_incoming_gettag(nta_incoming_t const *irq) { return irq ? irq->irq_tag : 0; } /** * Get status code of a server transaction. */ int nta_incoming_status(nta_incoming_t const *irq) { return irq ? irq->irq_status : 400; } /** Get application context for a server transaction. * * @param irq server transaction * @param callback callback pointer * * Return the application context bound to the server transaction. If the @a * callback function pointer is given, return application context only if * the callback matches with the callback bound to the server transaction. * */ nta_incoming_magic_t *nta_incoming_magic(nta_incoming_t *irq, nta_ack_cancel_f *callback) { return irq && (callback == NULL || irq->irq_callback == callback) ? irq->irq_magic : NULL; } /** When received. * * Return timestamp from the reception of the initial request. * * @NEW_1_12_7. */ sip_time_t nta_incoming_received(nta_incoming_t *irq, su_nanotime_t *return_nano) { su_time_t tv = { 0, 0 }; if (irq) tv = irq->irq_received; if (return_nano) *return_nano = (su_nanotime_t)tv.tv_sec * 1000000000 + tv.tv_usec * 1000; return tv.tv_sec; } /** Find incoming transaction. */ nta_incoming_t *nta_incoming_find(nta_agent_t const *agent, sip_t const *sip, sip_via_t const *v) { if (agent && sip && v) return incoming_find(agent, sip, v, NULL, NULL, NULL); else return NULL; } /** Find a matching server transaction object. * * Check also for requests to merge, to ACK, or to CANCEL. */ static nta_incoming_t *incoming_find(nta_agent_t const *agent, sip_t const *sip, sip_via_t const *v, nta_incoming_t **return_merge, nta_incoming_t **return_ack, nta_incoming_t **return_cancel) { sip_cseq_t const *cseq = sip->sip_cseq; sip_call_id_t const *i = sip->sip_call_id; sip_to_t const *to = sip->sip_to; sip_from_t const *from = sip->sip_from; sip_request_t *rq = sip->sip_request; incoming_htable_t const *iht = agent->sa_incoming; hash_value_t hash = NTA_HASH(i, cseq->cs_seq); char const *magic_branch; nta_incoming_t **ii, *irq; int is_uas_ack = return_ack && agent->sa_is_a_uas; if (v->v_branch && su_casenmatch(v->v_branch, "z9hG4bK", 7)) magic_branch = v->v_branch + 7; else magic_branch = NULL; for (ii = incoming_htable_hash(iht, hash); (irq = *ii); ii = incoming_htable_next(iht, ii)) { if (hash != irq->irq_hash || irq->irq_call_id->i_hash != i->i_hash || strcmp(irq->irq_call_id->i_id, i->i_id)) continue; if (irq->irq_cseq->cs_seq != cseq->cs_seq) continue; if (su_strcasecmp(irq->irq_from->a_tag, from->a_tag)) continue; if (is_uas_ack && irq->irq_method == sip_method_invite && 200 <= irq->irq_status && irq->irq_status < 300 && su_casematch(irq->irq_tag, to->a_tag)) { *return_ack = irq; return NULL; } if (magic_branch) { /* RFC3261 17.2.3: * * The request matches a transaction if branch and sent-by in topmost * the method of the request matches the one that created the * transaction, except for ACK, where the method of the request * that created the transaction is INVITE. */ if (irq->irq_via->v_branch && su_casematch(irq->irq_via->v_branch + 7, magic_branch) && su_casematch(irq->irq_via->v_host, v->v_host) && su_strmatch(irq->irq_via->v_port, v->v_port)) { if (irq->irq_method == cseq->cs_method && strcmp(irq->irq_cseq->cs_method_name, cseq->cs_method_name) == 0) return irq; if (return_ack && irq->irq_method == sip_method_invite) return *return_ack = irq, NULL; if (return_cancel && irq->irq_method != sip_method_ack) return *return_cancel = irq, NULL; } } else { /* No magic branch */ /* INVITE request matches a transaction if the Request-URI, To tag, From tag, Call-ID, CSeq, and top Via header match */ /* From tag, Call-ID, and CSeq number has been matched above */ /* Match top Via header field */ if (!su_casematch(irq->irq_via->v_branch, v->v_branch) || !su_casematch(irq->irq_via->v_host, v->v_host) || !su_strmatch(irq->irq_via->v_port, v->v_port)) ; /* Match Request-URI */ else if (url_cmp(irq->irq_rq->rq_url, rq->rq_url)) ; else { /* Match CSeq */ if (irq->irq_method == cseq->cs_method && su_strmatch(irq->irq_cseq->cs_method_name, cseq->cs_method_name)) { /* Match To tag */ if (!su_strcasecmp(irq->irq_to->a_tag, to->a_tag)) return irq; /* found */ } else if ( /* Tag set by UAS */ su_strcasecmp(irq->irq_tag, to->a_tag) && /* Original tag */ su_strcasecmp(irq->irq_to->a_tag, to->a_tag)) ; else if (return_ack && irq->irq_method == sip_method_invite) return *return_ack = irq, NULL; else if (return_cancel && irq->irq_method != sip_method_ack) return *return_cancel = irq, NULL; } } /* RFC3261 - section 8.2.2.2 Merged Requests */ if (return_merge) { if (irq->irq_cseq->cs_method == cseq->cs_method && strcmp(irq->irq_cseq->cs_method_name, cseq->cs_method_name) == 0) *return_merge = irq, return_merge = NULL; } } return NULL; } /** Process retransmitted requests. */ su_inline int incoming_recv(nta_incoming_t *irq, msg_t *msg, sip_t *sip, tport_t *tport) { nta_agent_t *agent = irq->irq_agent; agent->sa_stats->as_recv_retry++; if (irq->irq_status >= 100) { SU_DEBUG_5(("nta: re-received %s request, retransmitting %u reply\n", sip->sip_request->rq_method_name, irq->irq_status)); incoming_retransmit_reply(irq, tport); } else if (irq->irq_agent->sa_extra_100 && irq->irq_extra_100) { /* Agent and Irq configured to answer automatically with 100 Trying */ if (irq->irq_method == sip_method_invite || /* * Send 100 trying to non-invite if at least half of T2 has expired * since the transaction was created. */ su_duration(agent_now(irq->irq_agent), irq->irq_received) * 2U > irq->irq_agent->sa_t2) { SU_DEBUG_5(("nta: re-received %s request, sending 100 Trying\n", sip->sip_request->rq_method_name)); nta_incoming_treply(irq, SIP_100_TRYING, NTATAG_TPORT(tport), TAG_END()); } } msg_destroy(msg); return 0; } su_inline int incoming_ack(nta_incoming_t *irq, msg_t *msg, sip_t *sip, tport_t *tport) { nta_agent_t *agent = irq->irq_agent; /* Process ACK separately? */ if (irq->irq_status >= 200 && irq->irq_status < 300 && !agent->sa_is_a_uas) return -1; if (irq->irq_queue == agent->sa_in.inv_completed) { if (!irq->irq_confirmed) agent->sa_stats->as_acked_tr++; irq->irq_confirmed = 1; incoming_reset_timer(irq); /* Reset timer G */ if (!irq->irq_reliable_tp) { incoming_queue(agent->sa_in.inv_confirmed, irq); /* Timer I */ } else { irq->irq_terminated = 1; incoming_queue(agent->sa_in.terminated, irq); } if (!irq->irq_destroyed) { if (!irq->irq_callback) /* Process ACK normally */ return -1; incoming_call_callback(irq, msg, sip); /* ACK callback */ } } else if (irq->irq_queue == agent->sa_in.proceeding || irq->irq_queue == agent->sa_in.preliminary) return -1; else assert(irq->irq_queue == agent->sa_in.inv_confirmed || irq->irq_queue == agent->sa_in.terminated); msg_destroy(msg); return 0; } /** Respond to the CANCEL. */ su_inline int incoming_cancel(nta_incoming_t *irq, msg_t *msg, sip_t *sip, tport_t *tport) { nta_agent_t *agent = irq->irq_agent; /* According to the RFC 3261, this INVITE has been destroyed */ if (irq->irq_method == sip_method_invite && 200 <= irq->irq_status && irq->irq_status < 300) { mreply(agent, NULL, SIP_481_NO_TRANSACTION, msg, tport, 0, 0, NULL, TAG_END()); return 0; } /* UAS MUST use same tag in final response to CANCEL and INVITE */ if (agent->sa_is_a_uas && irq->irq_tag == NULL) { nta_incoming_tag(irq, NULL); } mreply(agent, NULL, SIP_200_OK, msg_ref(msg), tport, 0, 0, irq->irq_tag, TAG_END()); /* We have already sent final response */ if (irq->irq_completed || irq->irq_method != sip_method_invite) { msg_destroy(msg); return 0; } if (!irq->irq_canceled) { irq->irq_canceled = 1; agent->sa_stats->as_canceled_tr++; irq = incoming_call_callback(irq, msg, sip); } if (irq && !irq->irq_completed && agent->sa_cancel_487) /* Respond to the cancelled request */ nta_incoming_treply(irq, SIP_487_REQUEST_CANCELLED, TAG_END()); msg_destroy(msg); return 0; } /** Merge request */ static void request_merge(nta_agent_t *agent, msg_t *msg, sip_t *sip, tport_t *tport, char const *to_tag) { nta_incoming_t *irq; agent->sa_stats->as_merged_request++; irq = incoming_create(agent, msg, sip, tport, to_tag); if (irq) { nta_incoming_treply(irq, 482, "Request merged", TAG_END()); nta_incoming_destroy(irq); } else { SU_DEBUG_3(("nta: request_merge(): cannot create transaction for %s\n", sip->sip_request->rq_method_name)); mreply(agent, NULL, 482, "Request merged", msg, tport, 0, 0, NULL, TAG_END()); } } /**@typedef nta_ack_cancel_f * * Callback function prototype for CANCELed/ACKed requests * * This is a callback function is invoked by NTA when an incoming request * has been cancelled or an response to an incoming INVITE request has been * acknowledged. * * @param magic incoming request context * @param ireq incoming request * @param sip ACK/CANCEL message * * @retval 0 * This callback function should return always 0. */ /** Call callback of incoming transaction */ su_inline nta_incoming_t * incoming_call_callback(nta_incoming_t *irq, msg_t *msg, sip_t *sip) { if (irq->irq_callback) { irq->irq_in_callback = 1; irq->irq_request2 = msg; irq->irq_callback(irq->irq_magic, irq, sip); irq->irq_request2 = NULL; irq->irq_in_callback = 0; if (irq->irq_terminated && irq->irq_destroyed) incoming_free(irq), irq = NULL; } return irq; } /**Set server transaction parameters. * * Sets the server transaction parameters. Among others, parameters determine the way * the SigComp compression is handled. * * @TAGS * NTATAG_COMP(), NTATAG_SIGCOMP_CLOSE() and NTATAG_EXTRA_100(). * * @retval number of set parameters when succesful * @retval -1 upon an error */ int nta_incoming_set_params(nta_incoming_t *irq, tag_type_t tag, tag_value_t value, ...) { int retval = -1; if (irq) { ta_list ta; ta_start(ta, tag, value); retval = incoming_set_params(irq, ta_args(ta)); ta_end(ta); } else { su_seterrno(EINVAL); } return retval; } static int incoming_set_params(nta_incoming_t *irq, tagi_t const *tags) { int retval = 0; tagi_t const *t; char const *comp = NONE; struct sigcomp_compartment *cc = NONE; if (irq->irq_default) return retval; for (t = tags; t; t = tl_next(t)) { tag_type_t tt = t->t_tag; if (ntatag_comp == tt) comp = (char const *)t->t_value, retval++; else if (ntatag_sigcomp_close == tt) irq->irq_sigcomp_zap = t->t_value != 0, retval++; else if (tptag_compartment == tt) cc = (void *)t->t_value, retval++; else if (ntatag_extra_100 == tt) irq->irq_extra_100 = t->t_value != 0, retval++; } if (cc != NONE) { if (cc) agent_accept_compressed(irq->irq_agent, irq->irq_request, cc); if (irq->irq_cc) nta_compartment_decref(&irq->irq_cc); irq->irq_cc = nta_compartment_ref(cc); } else if (comp != NULL && comp != NONE && irq->irq_cc == NULL) { incoming_set_compartment(irq, irq->irq_tport, irq->irq_request, 1); } else if (comp == NULL) { irq->irq_tpn->tpn_comp = NULL; } return retval; } su_inline int incoming_set_compartment(nta_incoming_t *irq, tport_t *tport, msg_t *msg, int create_if_needed) { if (!nta_compressor_vtable) return 0; if (irq->irq_cc == NULL || irq->irq_tpn->tpn_comp || tport_delivered_with_comp(tport, msg, NULL) != -1) { struct sigcomp_compartment *cc; cc = agent_compression_compartment(irq->irq_agent, tport, irq->irq_tpn, create_if_needed); if (cc) agent_accept_compressed(irq->irq_agent, msg, cc); irq->irq_cc = cc; } return 0; } /** Add essential headers to the response message */ static int nta_incoming_response_headers(nta_incoming_t *irq, msg_t *msg, sip_t *sip) { int clone = 0; su_home_t *home = msg_home(msg); if (!sip->sip_from) clone = 1, sip->sip_from = sip_from_copy(home, irq->irq_from); if (!sip->sip_to) clone = 1, sip->sip_to = sip_to_copy(home, irq->irq_to); if (!sip->sip_call_id) clone = 1, sip->sip_call_id = sip_call_id_copy(home, irq->irq_call_id); if (!sip->sip_cseq) clone = 1, sip->sip_cseq = sip_cseq_copy(home, irq->irq_cseq); if (!sip->sip_via) clone = 1, sip->sip_via = sip_via_copy(home, irq->irq_via); if (clone) msg_set_parent(msg, (msg_t *)irq->irq_home); if (!sip->sip_from || !sip->sip_to || !sip->sip_call_id || !sip->sip_cseq || !sip->sip_via) return -1; return 0; } /** Complete a response message. * * @param irq server transaction object * @param msg response message to be completed * @param status status code (in range 100 - 699) * @param phrase status phrase (may be NULL) * @param tag,value,... taged argument list * * Generate status structure based on @a status and @a phrase. * Add essential headers to the response message: * @From, @To, @CallID, @CSeq, @Via, and optionally * @RecordRoute. */ int nta_incoming_complete_response(nta_incoming_t *irq, msg_t *msg, int status, char const *phrase, tag_type_t tag, tag_value_t value, ...) { su_home_t *home = msg_home(msg); sip_t *sip = sip_object(msg); int retval; ta_list ta; if (irq == NULL || sip == NULL) return su_seterrno(EFAULT); if (status != 0 && (status < 100 || status > 699)) return su_seterrno(EINVAL); if (status != 0 && !sip->sip_status) sip->sip_status = sip_status_create(home, status, phrase, NULL); ta_start(ta, tag, value); retval = sip_add_tl(msg, sip, ta_tags(ta)); ta_end(ta); if (retval < 0) return -1; if (irq->irq_default) return sip_complete_message(msg); if (status > 100 && !irq->irq_tag) { if (sip->sip_to) nta_incoming_tag(irq, sip->sip_to->a_tag); else nta_incoming_tag(irq, NULL); } if (nta_incoming_response_headers(irq, msg, sip) < 0) return -1; if (sip->sip_status && sip->sip_status->st_status > 100 && irq->irq_tag && sip->sip_to && !sip->sip_to->a_tag) if (sip_to_tag(home, sip->sip_to, irq->irq_tag) < 0) return -1; if (status < 300 && !sip->sip_record_route && irq->irq_record_route) if (sip_add_dup(msg, sip, (sip_header_t *)irq->irq_record_route) < 0) return -1; return sip_complete_message(msg); } /** Create a response message for request. * * @NEW_1_12_5. */ msg_t *nta_incoming_create_response(nta_incoming_t *irq, int status, char const *phrase) { msg_t *msg = NULL; sip_t *sip; if (irq) { msg = nta_msg_create(irq->irq_agent, 0); sip = sip_object(msg); if (sip) { if (status != 0) sip->sip_status = sip_status_create(msg_home(msg), status, phrase, NULL); if (nta_incoming_response_headers(irq, msg, sip) < 0) msg_destroy(msg), msg = NULL; } } return msg; } /**Reply to an incoming transaction request. * * This function creates a response message to an incoming request and sends * it to the client. * * @note * It is possible to send several non-final (1xx) responses, but only one * final response. * * @param irq incoming request * @param status status code * @param phrase status phrase (may be NULL if status code is well-known) * @param tag,value,... optional additional headers terminated by TAG_END() * * @retval 0 when succesful * @retval -1 upon an error */ int nta_incoming_treply(nta_incoming_t *irq, int status, char const *phrase, tag_type_t tag, tag_value_t value, ...) { int retval = -1; if (irq && (irq->irq_status < 200 || status < 200 || (irq->irq_method == sip_method_invite && status < 300))) { ta_list ta; msg_t *msg = nta_msg_create(irq->irq_agent, 0); ta_start(ta, tag, value); if (!msg) ; else if (nta_incoming_complete_response(irq, msg, status, phrase, ta_tags(ta)) < 0) msg_destroy(msg); else if (incoming_set_params(irq, ta_args(ta)) < 0) msg_destroy(msg); else retval = nta_incoming_mreply(irq, msg); ta_end(ta); if (retval < 0 && status >= 200) incoming_final_failed(irq, NULL); } return retval; } /** * Return a response message to client. * * @note * The ownership of @a msg is taken over by the function even if the * function fails. * * @retval 0 when succesful * @retval -1 upon an error */ int nta_incoming_mreply(nta_incoming_t *irq, msg_t *msg) { sip_t *sip = sip_object(msg); int status; if (irq == NULL) { msg_destroy(msg); return -1; } if (msg == NULL || sip == NULL) return -1; if (msg == irq->irq_response) return 0; if (!sip->sip_status || !sip->sip_via || !sip->sip_cseq) return incoming_final_failed(irq, msg); assert (sip->sip_cseq->cs_method == irq->irq_method || irq->irq_default); status = sip->sip_status->st_status; if (!irq->irq_tag && status > 100 && !irq->irq_default) nta_incoming_tag(irq, NULL); if (/* (irq->irq_confirmed && status >= 200) || */ (irq->irq_completed && status >= 300)) { SU_DEBUG_3(("%s: already %s transaction\n", __func__, irq->irq_confirmed ? "confirmed" : "completed")); msg_destroy(msg); return -1; } if (irq->irq_must_100rel && !sip->sip_rseq && status > 100 && status < 200) { /* This nta_reliable_t object will be destroyed by PRACK or timeout */ if (nta_reliable_mreply(irq, NULL, NULL, msg)) return 0; return -1; } if (status >= 200 && irq->irq_reliable && irq->irq_reliable->rel_unsent) { if (reliable_final(irq, msg, sip) == 0) return 0; } return incoming_reply(irq, msg, sip); } /** Send the response message. * * @note The ownership of msg is handled to incoming_reply(). */ int incoming_reply(nta_incoming_t *irq, msg_t *msg, sip_t *sip) { nta_agent_t *agent = irq->irq_agent; int status = sip->sip_status->st_status; int sending = 1; int *use_rport = NULL; int retry_without_rport = 0; tp_name_t *tpn, default_tpn[1]; if (status == 408 && irq->irq_method != sip_method_invite && !agent->sa_pass_408 && !irq->irq_default) { /* RFC 4320 nit-actions-03 Action 2: A transaction-stateful SIP element MUST NOT send a response with Status-Code of 408 to a non-INVITE request. As a consequence, an element that can not respond before the transaction expires will not send a final response at all. */ sending = 0; } if (irq->irq_status == 0 && irq->irq_timestamp && !sip->sip_timestamp) incoming_timestamp(irq, msg, sip); if (irq->irq_default) { if (agent->sa_server_rport) use_rport = &retry_without_rport, retry_without_rport = 1; tpn = default_tpn; if (nta_tpn_by_via(tpn, sip->sip_via, use_rport) < 0) tpn = NULL; } else { tpn = irq->irq_tpn; } if (sip_complete_message(msg) < 0) SU_DEBUG_1(("%s: sip_complete_message() failed\n", __func__)); else if (msg_serialize(msg, (msg_pub_t *)sip) < 0) SU_DEBUG_1(("%s: sip_serialize() failed\n", __func__)); else if (!(irq->irq_tport) && !(tport_decref(&irq->irq_tport), irq->irq_tport = tpn ? tport_by_name(agent->sa_tports, tpn) : 0)) SU_DEBUG_1(("%s: no tport\n", __func__)); else { int i, err = 0; tport_t *tp = NULL; incoming_queue_t *queue; char const *method_name; uint32_t cseq; if (irq->irq_default) { assert(sip->sip_cseq); method_name = sip->sip_cseq->cs_method_name, cseq = sip->sip_cseq->cs_seq; } else { method_name = irq->irq_rq->rq_method_name, cseq = irq->irq_cseq->cs_seq; } if (sending) { for (i = 0; i < 3; i++) { tp = tport_tsend(irq->irq_tport, msg, tpn, IF_SIGCOMP_TPTAG_COMPARTMENT(irq->irq_cc) TPTAG_MTU(INT_MAX), TAG_END()); if (tp) break; err = msg_errno(msg); SU_DEBUG_5(("%s: tport_tsend: %s%s\n", __func__, su_strerror(err), err == EPIPE ? "(retrying)" : "")); if (err != EPIPE && err != ECONNREFUSED) break; tport_decref(&irq->irq_tport); irq->irq_tport = tport_ref(tport_by_name(agent->sa_tports, tpn)); } if (!tp) { SU_DEBUG_3(("%s: tport_tsend: " "error (%s) while sending %u %s for %s (%u)\n", __func__, su_strerror(err), status, sip->sip_status->st_phrase, method_name, cseq)); if (status < 200) msg_destroy(msg); else incoming_final_failed(irq, msg); return 0; } agent->sa_stats->as_sent_msg++; agent->sa_stats->as_sent_response++; } SU_DEBUG_5(("nta: %s %u %s for %s (%u)\n", sending ? "sent" : "not sending", status, sip->sip_status->st_phrase, method_name, cseq)); if (irq->irq_default) { msg_destroy(msg); return 0; } incoming_reset_timer(irq); if (status < 200) { queue = agent->sa_in.proceeding; if (irq->irq_method == sip_method_invite && status > 100 && agent->sa_progress != UINT_MAX && agent->sa_is_a_uas) { /* Retransmit preliminary responses in regular intervals */ incoming_set_timer(irq, agent->sa_progress); /* N2 */ } } else { irq->irq_completed = 1; /* XXX - we should do this only after message has actually been sent! */ if (irq->irq_sigcomp_zap && irq->irq_cc) agent_close_compressor(irq->irq_agent, irq->irq_cc); if (irq->irq_method != sip_method_invite) { irq->irq_confirmed = 1; if (irq->irq_reliable_tp) { irq->irq_terminated = 1; queue = agent->sa_in.terminated ; /* J - set for 0 seconds */ } else { queue = agent->sa_in.completed; /* J */ } tport_decref(&irq->irq_tport); } else if (status >= 300 || agent->sa_is_a_uas) { if (status < 300 || !irq->irq_reliable_tp) incoming_set_timer(irq, agent->sa_t1); /* G */ queue = agent->sa_in.inv_completed; /* H */ } else { #if 1 /* Avoid bug in @RFC3261: Keep INVITE transaction around in order to catch retransmitted INVITEs */ irq->irq_confirmed = 1; queue = agent->sa_in.inv_confirmed; /* H */ #else irq->irq_terminated = 1; queue = agent->sa_in.terminated; #endif } } if (irq->irq_queue != queue) incoming_queue(queue, irq); if (status >= 200 || irq->irq_status < 200) { if (irq->irq_response) msg_destroy(irq->irq_response); assert(msg_home(msg) != irq->irq_home); irq->irq_response = msg; } else { msg_destroy(msg); } if (sip->sip_cseq->cs_method == irq->irq_method && irq->irq_status < 200 && status > irq->irq_status) irq->irq_status = status; return 0; } /* * XXX - handling error is very problematic. * Nobody checks return code from nta_incoming_*reply() */ if (status < 200) { msg_destroy(msg); return -1; } /* We could not send final response. */ return incoming_final_failed(irq, msg); } /** @internal Sending final response has failed. * * Put transaction into its own queue, try later to send the response. */ su_inline int incoming_final_failed(nta_incoming_t *irq, msg_t *msg) { msg_destroy(msg); if (!irq->irq_default) { irq->irq_final_failed = 1; incoming_queue(irq->irq_agent->sa_in.final_failed, irq); } return -1; } /** @internal Retransmit the reply */ static void incoming_retransmit_reply(nta_incoming_t *irq, tport_t *tport) { msg_t *msg = NULL; if (irq->irq_final_failed) return; if (tport == NULL) tport = irq->irq_tport; if (tport == NULL) return; /* Answer with existing reply */ if (irq->irq_reliable && !irq->irq_reliable->rel_pracked) msg = reliable_response(irq); else msg = irq->irq_response; if (msg == NULL) return; if (irq->irq_tpn->tpn_comp && ++irq->irq_retries == 2) { irq->irq_tpn->tpn_comp = NULL; if (irq->irq_cc) { agent_close_compressor(irq->irq_agent, irq->irq_cc); nta_compartment_decref(&irq->irq_cc); } } if (tport_tsend(tport, msg, irq->irq_tpn, IF_SIGCOMP_TPTAG_COMPARTMENT(irq->irq_cc) TPTAG_MTU(INT_MAX), TAG_END())) { irq->irq_agent->sa_stats->as_sent_msg++; irq->irq_agent->sa_stats->as_sent_response++; } } /** @internal Create timestamp header for response */ static int incoming_timestamp(nta_incoming_t *irq, msg_t *msg, sip_t *sip) { sip_timestamp_t ts[1]; su_time_t now = su_now(); char delay[32]; double diff = su_time_diff(now, irq->irq_received); snprintf(delay, sizeof delay, "%.06f", diff); *ts = *irq->irq_timestamp; ts->ts_delay = delay; return sip_add_dup(msg, sip, (sip_header_t *)ts); } enum { timer_max_retransmit = 30, timer_max_terminate = 100000, timer_max_timeout = 100 }; /** @internal Timer routine for the incoming request. */ static void _nta_incoming_timer(nta_agent_t *sa) { uint32_t now = sa->sa_millisec; nta_incoming_t *irq, *irq_next; size_t retransmitted = 0, timeout = 0, terminated = 0, destroyed = 0; size_t unconfirmed = sa->sa_in.inv_completed->q_length + sa->sa_in.preliminary->q_length; size_t unterminated = sa->sa_in.inv_confirmed->q_length + sa->sa_in.completed->q_length; size_t total = sa->sa_incoming->iht_used; incoming_queue_t rq[1]; incoming_queue_init(rq, 0); /* Handle retry queue */ while ((irq = sa->sa_in.re_list)) { if ((int32_t)(irq->irq_retry - now) > 0) break; if (retransmitted >= timer_max_retransmit) break; if (irq->irq_method == sip_method_invite && irq->irq_status >= 200) { /* Timer G */ assert(irq->irq_queue == sa->sa_in.inv_completed); retransmitted++; SU_DEBUG_5(("nta: timer %s fired, retransmitting %u reply\n", "G", irq->irq_status)); incoming_retransmit_reply(irq, irq->irq_tport); if (2U * irq->irq_interval < sa->sa_t2) incoming_set_timer(irq, 2U * irq->irq_interval); /* G */ else incoming_set_timer(irq, sa->sa_t2); /* G */ } else if (irq->irq_method == sip_method_invite && irq->irq_status >= 100) { if (irq->irq_queue == sa->sa_in.preliminary) { /* Timer P1 - PRACK timer */ retransmitted++; SU_DEBUG_5(("nta: timer %s fired, retransmitting %u reply\n", "P1", irq->irq_status)); incoming_retransmit_reply(irq, irq->irq_tport); incoming_set_timer(irq, 2 * irq->irq_interval); /* P1 */ } else { /* Retransmitting provisional responses */ SU_DEBUG_5(("nta: timer %s fired, retransmitting %u reply\n", "N2", irq->irq_status)); incoming_set_timer(irq, sa->sa_progress); retransmitted++; incoming_retransmit_reply(irq, irq->irq_tport); } } else { /* Timer N1 */ incoming_reset_timer(irq); if(irq->irq_extra_100) { SU_DEBUG_5(("nta: timer N1 fired, sending %u %s\n", SIP_100_TRYING)); nta_incoming_treply(irq, SIP_100_TRYING, TAG_END()); } else { SU_DEBUG_5(("nta: timer N1 fired, but avoided sending %u %s\n", SIP_100_TRYING)); } } } while ((irq = sa->sa_in.final_failed->q_head)) { incoming_remove(irq); irq->irq_final_failed = 0; /* Report error to application */ SU_DEBUG_5(("nta: sending final response failed, timeout %u response\n", irq->irq_status)); reliable_timeout(irq, 0); nta_incoming_treply(irq, SIP_500_INTERNAL_SERVER_ERROR, TAG_END()); if (!irq->irq_final_failed) /* We have taken care of the error... */ continue; if (irq->irq_destroyed) { incoming_free_queue(rq, irq); continue; } incoming_reset_timer(irq); irq->irq_confirmed = 1; irq->irq_terminated = 1; incoming_queue(sa->sa_in.terminated, irq); } /* Timeouts. * For each state the request is in, there is always a queue of its own */ while ((irq = sa->sa_in.preliminary->q_head)) { assert(irq->irq_status < 200); assert(irq->irq_timeout); if ((int32_t)(irq->irq_timeout - now) > 0) break; if (timeout >= timer_max_timeout) break; timeout++; /* Timer P2 - PRACK timer */ SU_DEBUG_5(("nta: timer %s fired, %s %u response\n", "P2", "timeout", irq->irq_status)); incoming_reset_timer(irq); irq->irq_timeout = 0; reliable_timeout(irq, 1); } while ((irq = sa->sa_in.inv_completed->q_head)) { assert(irq->irq_status >= 200); assert(irq->irq_timeout); assert(irq->irq_method == sip_method_invite); if ((int32_t)(irq->irq_timeout - now) > 0 || timeout >= timer_max_timeout || terminated >= timer_max_terminate) break; /* Timer H */ SU_DEBUG_5(("nta: timer %s fired, %s %u response\n", "H", "timeout and terminate", irq->irq_status)); irq->irq_confirmed = 1; irq->irq_terminated = 1; incoming_reset_timer(irq); if (!irq->irq_destroyed) { timeout++; incoming_queue(sa->sa_in.terminated, irq); /* report timeout error to user */ incoming_call_callback(irq, NULL, NULL); } else { timeout++; terminated++; incoming_free_queue(rq, irq); } } while ((irq = sa->sa_in.inv_confirmed->q_head)) { assert(irq->irq_timeout); assert(irq->irq_status >= 200); assert(irq->irq_method == sip_method_invite); if ((int32_t)(irq->irq_timeout - now) > 0 || terminated >= timer_max_terminate) break; /* Timer I */ SU_DEBUG_5(("nta: timer %s fired, %s %u response\n", "I", "terminate", irq->irq_status)); terminated++; irq->irq_terminated = 1; if (!irq->irq_destroyed) incoming_queue(sa->sa_in.terminated, irq); else incoming_free_queue(rq, irq); } while ((irq = sa->sa_in.completed->q_head)) { assert(irq->irq_status >= 200); assert(irq->irq_timeout); assert(irq->irq_method != sip_method_invite); if ((int32_t)(irq->irq_timeout - now) > 0 || terminated >= timer_max_terminate) break; /* Timer J */ SU_DEBUG_5(("nta: timer %s fired, %s %u response\n", "J", "terminate", irq->irq_status)); terminated++; irq->irq_terminated = 1; if (!irq->irq_destroyed) incoming_queue(sa->sa_in.terminated, irq); else incoming_free_queue(rq, irq); } for (irq = sa->sa_in.terminated->q_head; irq; irq = irq_next) { irq_next = irq->irq_next; if (irq->irq_destroyed) incoming_free_queue(rq, irq); } destroyed = incoming_mass_destroy(sa, rq); if (retransmitted || timeout || terminated || destroyed) SU_DEBUG_5(("nta_incoming_timer: " MOD_ZU"/"MOD_ZU" resent, " MOD_ZU"/"MOD_ZU" tout, " MOD_ZU"/"MOD_ZU" term, " MOD_ZU"/"MOD_ZU" free\n", retransmitted, unconfirmed, timeout, unconfirmed, terminated, unterminated, destroyed, total)); } /** Mass destroy server transactions */ su_inline size_t incoming_mass_destroy(nta_agent_t *sa, incoming_queue_t *q) { size_t destroyed = q->q_length; if (destroyed > 2 && *sa->sa_terminator) { su_msg_r m = SU_MSG_R_INIT; if (su_msg_create(m, su_clone_task(sa->sa_terminator), su_root_task(sa->sa_root), incoming_reclaim_queued, sizeof(incoming_queue_t)) == SU_SUCCESS) { incoming_queue_t *mq = su_msg_data(m)->a_incoming_queue; *mq = *q; if (su_msg_send(m) == SU_SUCCESS) q->q_length = 0; } } if (q->q_length > 0) incoming_reclaim_queued(NULL, NULL, (void *)q); return destroyed; } /* ====================================================================== */ /* 8) Client-side (outgoing) transactions */ #define HTABLE_HASH_ORQ(orq) ((orq)->orq_hash) HTABLE_BODIES_WITH(outgoing_htable, oht, nta_outgoing_t, HTABLE_HASH_ORQ, size_t, hash_value_t); static int outgoing_features(nta_agent_t *agent, nta_outgoing_t *orq, msg_t *msg, sip_t *sip, tagi_t *tags); static void outgoing_prepare_send(nta_outgoing_t *orq); static void outgoing_send_via(nta_outgoing_t *orq, tport_t *tp); static void outgoing_send(nta_outgoing_t *orq, int retransmit); static void outgoing_try_tcp_instead(nta_outgoing_t *orq); static void outgoing_try_udp_instead(nta_outgoing_t *orq, int timeout); static void outgoing_tport_error(nta_agent_t *agent, nta_outgoing_t *orq, tport_t *tp, msg_t *msg, int error); static void outgoing_print_tport_error(nta_outgoing_t *orq, int level, char *todo, tp_name_t const *, msg_t *, int error); static void outgoing_insert(nta_agent_t *sa, nta_outgoing_t *orq); static void outgoing_destroy(nta_outgoing_t *orq); su_inline int outgoing_is_queued(nta_outgoing_t const *orq); su_inline void outgoing_queue(outgoing_queue_t *queue, nta_outgoing_t *orq); su_inline void outgoing_remove(nta_outgoing_t *orq); su_inline void outgoing_set_timer(nta_outgoing_t *orq, uint32_t interval); static void outgoing_reset_timer(nta_outgoing_t *orq); static size_t outgoing_timer_dk(outgoing_queue_t *q, char const *timer, uint32_t now); static size_t outgoing_timer_bf(outgoing_queue_t *q, char const *timer, uint32_t now); static size_t outgoing_timer_c(outgoing_queue_t *q, char const *timer, uint32_t now); static void outgoing_ack(nta_outgoing_t *orq, sip_t *sip); static msg_t *outgoing_ackmsg(nta_outgoing_t *, sip_method_t, char const *, tag_type_t tag, tag_value_t value, ...); static void outgoing_retransmit(nta_outgoing_t *orq); static void outgoing_trying(nta_outgoing_t *orq); static void outgoing_timeout(nta_outgoing_t *orq, uint32_t now); static int outgoing_complete(nta_outgoing_t *orq); static void outgoing_terminate_invite(nta_outgoing_t *); static void outgoing_remove_fork(nta_outgoing_t *orq); static int outgoing_terminate(nta_outgoing_t *orq); static size_t outgoing_mass_destroy(nta_agent_t *sa, outgoing_queue_t *q); static void outgoing_estimate_delay(nta_outgoing_t *orq, sip_t *sip); static int outgoing_duplicate(nta_outgoing_t *orq, msg_t *msg, sip_t *sip); static int outgoing_reply(nta_outgoing_t *orq, int status, char const *phrase, int delayed); static int outgoing_default_cb(nta_outgoing_magic_t *magic, nta_outgoing_t *request, sip_t const *sip); #if HAVE_SOFIA_SRESOLV static void outgoing_resolve(nta_outgoing_t *orq, int explicit_transport, enum nta_res_order_e order); su_inline void outgoing_cancel_resolver(nta_outgoing_t *orq); su_inline void outgoing_destroy_resolver(nta_outgoing_t *orq); static int outgoing_other_destinations(nta_outgoing_t const *orq); static int outgoing_try_another(nta_outgoing_t *orq); #else #define outgoing_other_destinations(orq) (0) #define outgoing_try_another(orq) (0) #define outgoing_cancel_resolver(orq) ((void)0) #endif /** Create a default outgoing transaction. * * The default outgoing transaction is used when agent receives responses * not belonging to any transaction. * * @sa nta_leg_default(), nta_incoming_default(). */ nta_outgoing_t *nta_outgoing_default(nta_agent_t *agent, nta_response_f *callback, nta_outgoing_magic_t *magic) { nta_outgoing_t *orq; if (agent == NULL) return NULL; if (agent->sa_default_outgoing) return NULL; orq = su_zalloc(agent->sa_home, sizeof *orq); if (!orq) return NULL; orq->orq_agent = agent; orq->orq_callback = callback; orq->orq_magic = magic; orq->orq_method = sip_method_invalid; orq->orq_method_name = "*"; orq->orq_default = 1; orq->orq_stateless = 1; orq->orq_delay = UINT_MAX; return agent->sa_default_outgoing = orq; } /**Create an outgoing request and client transaction belonging to the leg. * * Create a request message and pass the request message to an outgoing * client transaction object. The request is sent to the @a route_url (if * non-NULL), default proxy (if defined by NTATAG_DEFAULT_PROXY()), or to * the address specified by @a request_uri. If no @a request_uri is * specified, it is taken from route-set target or from the @To header. * * When NTA receives response to the request, it invokes the @a callback * function. * * @param leg call leg object * @param callback callback function (may be @c NULL) * @param magic application context pointer * @param route_url optional URL used to route transaction requests * @param method method type * @param name method name * @param request_uri Request-URI * @param tag, value, ... list of tagged arguments * * @return * A pointer to a newly created outgoing transaction object if successful, * and NULL otherwise. * * @note If NTATAG_STATELESS(1) tag is given and the @a callback is NULL, * the transaction object is marked as destroyed from the beginning. In that * case, the function may return @code (nta_outgoing_t *)-1 @endcode if the * transaction is freed before returning from the function. * * @sa * nta_outgoing_mcreate(), nta_outgoing_tcancel(), nta_outgoing_destroy(). * * @TAGS * NTATAG_STATELESS(), NTATAG_DELAY_SENDING(), NTATAG_BRANCH_KEY(), * NTATAG_ACK_BRANCH(), NTATAG_DEFAULT_PROXY(), NTATAG_PASS_100(), * NTATAG_USE_TIMESTAMP(), NTATAG_USER_VIA(), TPTAG_IDENT(), NTATAG_TPORT(). All * SIP tags from <sofia-sip/sip_tag.h> can be used to manipulate the request message. * SIP tags after SIPTAG_END() are ignored, however. */ nta_outgoing_t *nta_outgoing_tcreate(nta_leg_t *leg, nta_response_f *callback, nta_outgoing_magic_t *magic, url_string_t const *route_url, sip_method_t method, char const *name, url_string_t const *request_uri, tag_type_t tag, tag_value_t value, ...) { nta_agent_t *agent; msg_t *msg; sip_t *sip; nta_outgoing_t *orq = NULL; ta_list ta; tagi_t const *tagi; if (leg == NULL) return NULL; agent = leg->leg_agent; msg = nta_msg_create(agent, 0); sip = sip_object(msg); if (route_url == NULL) route_url = (url_string_t *)agent->sa_default_proxy; ta_start(ta, tag, value); tagi = ta_args(ta); if (sip_add_tagis(msg, sip, &tagi) < 0) { if (tagi && tagi->t_tag) { tag_type_t t = tagi->t_tag; SU_DEBUG_5(("%s(): bad tag %s::%s\n", __func__, t->tt_ns ? t->tt_ns : "", t->tt_name ? t->tt_name : "")); } } else if (route_url == NULL && leg->leg_route && leg->leg_loose_route && !(route_url = (url_string_t *)leg->leg_route->r_url)) ; else if (nta_msg_request_complete(msg, leg, method, name, request_uri) < 0) ; else orq = outgoing_create(agent, callback, magic, route_url, NULL, msg, ta_tags(ta)); ta_end(ta); if (!orq) msg_destroy(msg); return orq; } /**Create an outgoing client transaction. * * Create an outgoing transaction object. The request message is passed to * the transaction object, which sends the request to the network. The * request is sent to the @a route_url (if non-NULL), default proxy (if * defined by NTATAG_DEFAULT_PROXY()), or to the address specified by @a * request_uri. If no @a request_uri is specified, it is taken from * route-set target or from the @To header. * * When NTA receives response to the request, it invokes the @a callback * function. * * @param agent NTA agent object * @param callback callback function (may be @c NULL) * @param magic application context pointer * @param route_url optional URL used to route transaction requests * @param msg request message * @param tag, value, ... tagged parameter list * * @return * Returns a pointer to newly created outgoing transaction object if * successful, and NULL otherwise. * * @note The caller is responsible for destroying the request message @a msg * upon failure. * * @note If NTATAG_STATELESS(1) tag is given and the @a callback is NULL, * the transaction object is marked as destroyed from the beginning. In that * case, the function may return @code (nta_outgoing_t *)-1 @endcode if the * transaction is freed before returning from the function. * * @sa * nta_outgoing_tcreate(), nta_outgoing_tcancel(), nta_outgoing_destroy(). * * @TAGS * NTATAG_STATELESS(), NTATAG_DELAY_SENDING(), NTATAG_BRANCH_KEY(), * NTATAG_ACK_BRANCH(), NTATAG_DEFAULT_PROXY(), NTATAG_PASS_100(), * NTATAG_USE_TIMESTAMP(), NTATAG_USER_VIA(), TPTAG_IDENT(), NTATAG_TPORT(). All * SIP tags from <sofia-sip/sip_tag.h> can be used to manipulate the request message. * SIP tags after SIPTAG_END() are ignored, however. */ nta_outgoing_t *nta_outgoing_mcreate(nta_agent_t *agent, nta_response_f *callback, nta_outgoing_magic_t *magic, url_string_t const *route_url, msg_t *msg, tag_type_t tag, tag_value_t value, ...) { nta_outgoing_t *orq = NULL; int cleanup = 0; if (msg == NONE) msg = nta_msg_create(agent, 0), cleanup = 1; if (msg && agent) { ta_list ta; ta_start(ta, tag, value); if (sip_add_tl(msg, sip_object(msg), ta_tags(ta)) >= 0) orq = outgoing_create(agent, callback, magic, route_url, NULL, msg, ta_tags(ta)); ta_end(ta); } if (!orq && cleanup) msg_destroy(msg); return orq; } /** Cancel the request. */ int nta_outgoing_cancel(nta_outgoing_t *orq) { nta_outgoing_t *cancel = nta_outgoing_tcancel(orq, NULL, NULL, TAG_NULL()); return (cancel != NULL) - 1; } /** Cancel the request. * * Initiate a cancel transaction for client transaction @a orq. * * @param orq client transaction to cancel * @param callback callback function (may be @c NULL) * @param magic application context pointer * @param tag, value, ... list of extra arguments * * @note The function may return @code (nta_outgoing_t *)-1 @endcode (NONE) * if callback is NULL. * * @TAGS * NTATAG_CANCEL_2534(), NTATAG_CANCEL_408() and all the tags that are * accepted by nta_outgoing_tcreate(). * * If NTATAG_CANCEL_408(1) or NTATAG_CANCEL_2543(1) is given, the stack * generates a 487 response to the request internally. If * NTATAG_CANCEL_408(1) is given, no CANCEL request is actually sent. * * @note * nta_outgoing_tcancel() refuses to send a CANCEL request for non-INVITE * requests. */ nta_outgoing_t *nta_outgoing_tcancel(nta_outgoing_t *orq, nta_response_f *callback, nta_outgoing_magic_t *magic, tag_type_t tag, tag_value_t value, ...) { msg_t *msg; int cancel_2543, cancel_408; ta_list ta; int delay_sending; if (orq == NULL || orq == NONE) return NULL; if (orq->orq_destroyed) { SU_DEBUG_3(("%s: trying to cancel destroyed request\n", __func__)); return NULL; } if (orq->orq_method != sip_method_invite) { SU_DEBUG_3(("%s: trying to cancel non-INVITE request\n", __func__)); return NULL; } if (orq->orq_forking) orq = orq->orq_forking; if (orq->orq_status >= 200 /* && orq->orq_method != sip_method_invite ... !multicast */) { SU_DEBUG_3(("%s: trying to cancel completed request\n", __func__)); return NULL; } if (orq->orq_canceled) { SU_DEBUG_3(("%s: trying to cancel cancelled request\n", __func__)); return NULL; } orq->orq_canceled = 1; #if HAVE_SOFIA_SRESOLV if (!orq->orq_resolved) { outgoing_destroy_resolver(orq); outgoing_reply(orq, SIP_487_REQUEST_CANCELLED, 1); return NULL; /* XXX - Does anyone care about reply? */ } #endif cancel_408 = 0; /* Don't really CANCEL, this is timeout. */ cancel_2543 = orq->orq_agent->sa_cancel_2543; /* CANCEL may be sent only after a provisional response has been received. */ delay_sending = orq->orq_status < 100; ta_start(ta, tag, value); tl_gets(ta_args(ta), NTATAG_CANCEL_408_REF(cancel_408), NTATAG_CANCEL_2543_REF(cancel_2543), TAG_END()); if (!cancel_408) msg = outgoing_ackmsg(orq, SIP_METHOD_CANCEL, ta_tags(ta)); else msg = NULL; ta_end(ta); if ((cancel_2543 || cancel_408) && !orq->orq_stateless) outgoing_reply(orq, SIP_487_REQUEST_CANCELLED, 1); if (msg) { nta_outgoing_t *cancel; if (cancel_2543) /* Follow RFC 2543 semantics for CANCEL */ delay_sending = 0; cancel = outgoing_create(orq->orq_agent, callback, magic, NULL, orq->orq_tpn, msg, NTATAG_BRANCH_KEY(orq->orq_branch), NTATAG_DELAY_SENDING(delay_sending), NTATAG_USER_VIA(1), TAG_END()); if (delay_sending) orq->orq_cancel = cancel; if (cancel) { if (!delay_sending) outgoing_complete(orq); return cancel; } msg_destroy(msg); } return NULL; } /**Bind callback and application context to a client transaction. * * @param orq outgoing client transaction * @param callback callback function (may be NULL) * @param magic application context pointer * (given as argument to @a callback) * * @NEW_1_12_9 */ int nta_outgoing_bind(nta_outgoing_t *orq, nta_response_f *callback, nta_outgoing_magic_t *magic) { if (orq && !orq->orq_destroyed) { if (callback == NULL) callback = outgoing_default_cb; orq->orq_callback = callback; orq->orq_magic = magic; return 0; } return -1; } /**Get application context bound to a client transaction. * * @param orq outgoing client transaction * @param callback callback function (may be NULL) * * Return the application context bound to a client transaction. If the @a * callback function pointer is given, return application context only if * the callback matches with the callback bound to the client transaction. * * @NEW_1_12_11 */ nta_outgoing_magic_t * nta_outgoing_magic(nta_outgoing_t const *orq, nta_response_f *callback) { if (orq && (callback == NULL || callback == orq->orq_callback)) return orq->orq_magic; else return NULL; } /** * Destroy a request object. * * @note * This function does not actually free the object, but marks it as * disposable. The object is freed after a timeout. */ void nta_outgoing_destroy(nta_outgoing_t *orq) { if (orq == NULL || orq == NONE) return; if (orq->orq_destroyed) { SU_DEBUG_1(("%s(%p): %s\n", "nta_outgoing_destroy", (void *)orq, "already destroyed")); return; } outgoing_destroy(orq); } /** Return the request URI */ url_t const *nta_outgoing_request_uri(nta_outgoing_t const *orq) { return orq != NULL && orq != NONE ? orq->orq_url : NULL; } /** Return the URI used to route the request */ url_t const *nta_outgoing_route_uri(nta_outgoing_t const *orq) { return orq != NULL && orq != NONE ? orq->orq_route : NULL; } /** Return method of the client transaction */ sip_method_t nta_outgoing_method(nta_outgoing_t const *orq) { return orq != NULL && orq != NONE ? orq->orq_method : sip_method_invalid; } /** Return method name of the client transaction */ char const *nta_outgoing_method_name(nta_outgoing_t const *orq) { return orq != NULL && orq != NONE ? orq->orq_method_name : NULL; } /** Get sequence number of a client transaction. */ uint32_t nta_outgoing_cseq(nta_outgoing_t const *orq) { return orq != NULL && orq != NONE && orq->orq_cseq ? orq->orq_cseq->cs_seq : 0; } /** * Get the status code of a client transaction. */ int nta_outgoing_status(nta_outgoing_t const *orq) { /* Return 500 Internal server error for invalid handles. */ return orq != NULL && orq != NONE ? orq->orq_status : 500; } /** Get the RTT delay measured using @Timestamp header. */ unsigned nta_outgoing_delay(nta_outgoing_t const *orq) { return orq != NULL && orq != NONE ? orq->orq_delay : UINT_MAX; } /** Get the branch parameter. @NEW_1_12_7. */ char const *nta_outgoing_branch(nta_outgoing_t const *orq) { return orq != NULL && orq != NONE && orq->orq_branch ? orq->orq_branch + strlen("branch=") : NULL; } /**Get reference to response message. * * Retrieve the latest incoming response message to the outgoing * transaction. Note that the message is not copied, but a new reference to * it is created instead. * * @param orq outgoing transaction handle * * @retval * A pointer to response message is returned, or NULL if no response message * has been received. */ msg_t *nta_outgoing_getresponse(nta_outgoing_t *orq) { if (orq != NULL && orq != NONE) return msg_ref(orq->orq_response); else return NULL; } /**Get request message. * * Retrieves the request message sent to the network. Note that the request * message is @b not copied, but a new reference to it is created. * * @retval * A pointer to the request message is returned, or NULL if an error * occurred. */ msg_t *nta_outgoing_getrequest(nta_outgoing_t *orq) { if (orq != NULL && orq != NONE) return msg_ref(orq->orq_request); else return NULL; } /**Create an outgoing request. * * Create an outgoing transaction object and send the request to the * network. The request is sent to the @a route_url (if non-NULL), default * proxy (if defined by NTATAG_DEFAULT_PROXY()), or to the address specified * by @a sip->sip_request->rq_url. * * When NTA receives response to the request, it invokes the @a callback * function. * * @param agent nta agent object * @param callback callback function (may be @c NULL) * @param magic application context pointer * @param route_url optional URL used to route transaction requests * @param msg request message * @param tpn (optional) transport name * @param msg request message to * @param tag, value, ... tagged arguments * * @return * Returns a pointer to newly created outgoing transaction object if * successful, and NULL otherwise. * * @note If NTATAG_STATELESS(1) tag is given and the @a callback is NULL, * the transaction object is marked as destroyed from the beginning. In that * case, the function may return @code (nta_outgoing_t *)-1 @endcode if the * transaction is freed before returning from the function. * * @TAG NTATAG_TPORT must point to an existing transport object for * 'agent' (the passed tport is otherwise ignored). * * @sa * nta_outgoing_tcreate(), nta_outgoing_tcancel(), nta_outgoing_destroy(). */ nta_outgoing_t *outgoing_create(nta_agent_t *agent, nta_response_f *callback, nta_outgoing_magic_t *magic, url_string_t const *route_url, tp_name_t const *tpn, msg_t *msg, tag_type_t tag, tag_value_t value, ...) { nta_outgoing_t *orq; sip_t *sip; su_home_t *home; char const *comp = NONE; char const *branch = NONE; char const *ack_branch = NONE; char const *tp_ident; int delay_sending = 0, sigcomp_zap = 0; int pass_100 = agent->sa_pass_100, use_timestamp = agent->sa_timestamp; enum nta_res_order_e res_order = agent->sa_res_order; struct sigcomp_compartment *cc = NULL; ta_list ta; char const *scheme = NULL; char const *port = NULL; int invalid, resolved = 0, stateless = 0, user_via = agent->sa_user_via; int invite_100rel = agent->sa_invite_100rel; int explicit_transport = 1; tagi_t const *t; tport_t *override_tport = NULL; if (!agent->sa_tport_ip6) res_order = nta_res_ip4_only; else if (!agent->sa_tport_ip4) res_order = nta_res_ip6_only; if (!callback) callback = outgoing_default_cb; if (!route_url) route_url = (url_string_t *)agent->sa_default_proxy; sip = sip_object(msg); home = msg_home(msg); if (!sip->sip_request || sip_complete_message(msg) < 0) { SU_DEBUG_3(("nta: outgoing_create: incomplete request\n")); return NULL; } if (!route_url && !tpn && sip->sip_route && sip->sip_route->r_url->url_params && url_param(sip->sip_route->r_url->url_params, "lr", NULL, 0)) route_url = (url_string_t *)sip->sip_route->r_url; if (!(orq = su_zalloc(agent->sa_home, sizeof(*orq)))) return NULL; tp_ident = tpn ? tpn->tpn_ident : NULL; ta_start(ta, tag, value); /* tl_gets() is a bit too slow here... */ for (t = ta_args(ta); t; t = tl_next(t)) { tag_type_t tt = t->t_tag; if (ntatag_stateless == tt) stateless = t->t_value != 0; else if (ntatag_delay_sending == tt) delay_sending = t->t_value != 0; else if (ntatag_branch_key == tt) branch = (void *)t->t_value; else if (ntatag_pass_100 == tt) pass_100 = t->t_value != 0; else if (ntatag_use_timestamp == tt) use_timestamp = t->t_value != 0; else if (ntatag_user_via == tt) user_via = t->t_value != 0; else if (ntatag_ack_branch == tt) ack_branch = (void *)t->t_value; else if (ntatag_default_proxy == tt) route_url = (void *)t->t_value; else if (tptag_ident == tt) tp_ident = (void *)t->t_value; else if (ntatag_comp == tt) comp = (char const *)t->t_value; else if (ntatag_sigcomp_close == tt) sigcomp_zap = t->t_value != 0; else if (tptag_compartment == tt) cc = (void *)t->t_value; else if (ntatag_tport == tt) { override_tport = (tport_t *)t->t_value; } else if (ntatag_rel100 == tt) { invite_100rel = t->t_value != 0; } } orq->orq_agent = agent; orq->orq_callback = callback; orq->orq_magic = magic; orq->orq_method = sip->sip_request->rq_method; orq->orq_method_name = sip->sip_request->rq_method_name; orq->orq_cseq = sip->sip_cseq; orq->orq_to = sip->sip_to; orq->orq_from = sip->sip_from; orq->orq_call_id = sip->sip_call_id; orq->orq_tags = tl_afilter(home, tport_tags, ta_args(ta)); orq->orq_delayed = delay_sending != 0; orq->orq_pass_100 = pass_100 != 0; orq->orq_sigcomp_zap = sigcomp_zap; orq->orq_sigcomp_new = comp != NONE && comp != NULL; orq->orq_timestamp = use_timestamp; orq->orq_delay = UINT_MAX; orq->orq_stateless = stateless != 0; orq->orq_user_via = user_via != 0 && sip->sip_via; orq->orq_100rel = invite_100rel; orq->orq_uas = !stateless && agent->sa_is_a_uas; if (cc) orq->orq_cc = nta_compartment_ref(cc); /* Add supported features */ outgoing_features(agent, orq, msg, sip, ta_args(ta)); ta_end(ta); /* select the tport to use for the outgoing message */ if (override_tport) { /* note: no ref taken to the tport as its only used once here */ if (tport_is_secondary(override_tport)) { tpn = tport_name(override_tport); orq->orq_user_tport = 1; } } if (tpn) { /* CANCEL or ACK to [3456]XX */ invalid = tport_name_dup(home, orq->orq_tpn, tpn); #if 0 /* XXX - HAVE_SOFIA_SRESOLV */ /* We send ACK or CANCEL only if original request was really sent */ assert(tport_name_is_resolved(orq->orq_tpn)); #endif resolved = tport_name_is_resolved(orq->orq_tpn); orq->orq_url = url_hdup(home, sip->sip_request->rq_url); } else if (route_url && !orq->orq_user_tport) { invalid = nta_tpn_by_url(home, orq->orq_tpn, &scheme, &port, route_url); if (invalid >= 0) { explicit_transport = invalid > 0; if (override_tport) { /* Use transport protocol name from transport */ if (strcmp(orq->orq_tpn->tpn_proto, "*") == 0) orq->orq_tpn->tpn_proto = tport_name(override_tport)->tpn_proto; } resolved = tport_name_is_resolved(orq->orq_tpn); orq->orq_url = url_hdup(home, sip->sip_request->rq_url); if (route_url != (url_string_t *)agent->sa_default_proxy) orq->orq_route = url_hdup(home, route_url->us_url); } } else { invalid = nta_tpn_by_url(home, orq->orq_tpn, &scheme, &port, (url_string_t *)sip->sip_request->rq_url); if (invalid >= 0) { explicit_transport = invalid > 0; resolved = tport_name_is_resolved(orq->orq_tpn); msg_fragment_clear(sip->sip_request->rq_common); } orq->orq_url = url_hdup(home, sip->sip_request->rq_url); } if (!override_tport) orq->orq_tpn->tpn_ident = tp_ident; else orq->orq_tpn->tpn_ident = tport_name(override_tport)->tpn_ident; if (comp == NULL) orq->orq_tpn->tpn_comp = comp; if (orq->orq_user_via && su_strmatch(orq->orq_tpn->tpn_proto, "*")) { char const *proto = sip_via_transport(sip->sip_via); if (proto) orq->orq_tpn->tpn_proto = proto; } if (branch && branch != NONE) { if (su_casenmatch(branch, "branch=", 7)) branch = su_strdup(home, branch); else branch = su_sprintf(home, "branch=%s", branch); } else if (orq->orq_user_via && sip->sip_via->v_branch) branch = su_sprintf(home, "branch=%s", sip->sip_via->v_branch); else if (stateless) branch = stateless_branch(agent, msg, sip, orq->orq_tpn); else branch = stateful_branch(home, agent); orq->orq_branch = branch; orq->orq_via_branch = branch; if (orq->orq_method == sip_method_ack) { /* Find the original INVITE which we are ACKing */ if (ack_branch != NULL && ack_branch != NONE) { if (su_casenmatch(ack_branch, "branch=", 7)) orq->orq_branch = su_strdup(home, ack_branch); else orq->orq_branch = su_sprintf(home, "branch=%s", ack_branch); } else if (orq->orq_uas) { /* * ACK redirects further 2XX messages to it. * * Use orq_branch from INVITE, but put a different branch in topmost Via. */ nta_outgoing_t *invite = outgoing_find(agent, msg, sip, NULL); if (invite) { sip_t const *inv = sip_object(invite->orq_request); orq->orq_branch = su_strdup(home, invite->orq_branch); /* @RFC3261 section 13.2.2.4 - * The ACK MUST contain the same credentials as the INVITE. */ if (!sip->sip_proxy_authorization && !sip->sip_authorization) { if (inv->sip_proxy_authorization) sip_add_dup(msg, sip, (void *)inv->sip_proxy_authorization); if (inv->sip_authorization) sip_add_dup(msg, sip, (void *)inv->sip_authorization); } } else { SU_DEBUG_1(("outgoing_create: ACK without INVITE\n")); assert(!"INVITE found for ACK"); } } } #if HAVE_SOFIA_SRESOLV if (!resolved) orq->orq_tpn->tpn_port = port; orq->orq_resolved = resolved; #else orq->orq_resolved = resolved = 1; #endif orq->orq_sips = su_casematch(scheme, "sips"); if (invalid < 0 || !orq->orq_branch || msg_serialize(msg, (void *)sip) < 0) { SU_DEBUG_3(("nta outgoing create: %s\n", invalid < 0 ? "invalid URI" : !orq->orq_branch ? "no branch" : "invalid message")); outgoing_free(orq); return NULL; } /* Now we are committed in sending the transaction */ orq->orq_request = msg; agent->sa_stats->as_client_tr++; orq->orq_hash = NTA_HASH(sip->sip_call_id, sip->sip_cseq->cs_seq); if (orq->orq_user_tport) outgoing_send_via(orq, override_tport); else if (resolved) outgoing_prepare_send(orq); #if HAVE_SOFIA_SRESOLV else outgoing_resolve(orq, explicit_transport, res_order); #endif if (stateless && orq->orq_status >= 200 && callback == outgoing_default_cb) { void *retval; if (orq->orq_status < 300) retval = (void *)-1; /* NONE */ else retval = NULL, orq->orq_request = NULL; outgoing_free(orq); return retval; } assert(orq->orq_queue); outgoing_insert(agent, orq); return orq; } /** Prepare sending a request */ static void outgoing_prepare_send(nta_outgoing_t *orq) { nta_agent_t *sa = orq->orq_agent; tport_t *tp; tp_name_t *tpn = orq->orq_tpn; /* Select transport by scheme */ if (orq->orq_sips && strcmp(tpn->tpn_proto, "*") == 0) tpn->tpn_proto = "tls"; if (!tpn->tpn_port) tpn->tpn_port = ""; tp = tport_by_name(sa->sa_tports, tpn); if (tpn->tpn_port[0] == '\0') { if (orq->orq_sips || tport_has_tls(tp)) tpn->tpn_port = "5061"; else tpn->tpn_port = "5060"; } if (tp) { outgoing_send_via(orq, tp); } else if (orq->orq_sips) { SU_DEBUG_3(("nta outgoing create: no secure transport\n")); outgoing_reply(orq, SIP_416_UNSUPPORTED_URI, 1); } else { SU_DEBUG_3(("nta outgoing create: no transport protocol\n")); outgoing_reply(orq, 503, "No transport", 1); } } /** Send request using given transport */ static void outgoing_send_via(nta_outgoing_t *orq, tport_t *tp) { tport_t *old_tp = orq->orq_tport; orq->orq_tport = tport_ref(tp); if (orq->orq_pending && tp != old_tp) { tport_release(old_tp, orq->orq_pending, orq->orq_request, NULL, orq, 0); orq->orq_pending = 0; } if (old_tp) tport_unref(old_tp); if (outgoing_insert_via(orq, agent_tport_via(tp)) < 0) { SU_DEBUG_3(("nta outgoing create: cannot insert Via line\n")); outgoing_reply(orq, 503, "Cannot insert Via", 1); return; } #if HAVE_SOFIA_SMIME { sm_object_t *smime = sa->sa_smime; sip_t *sip = sip_object(orq->orq_request); if (sa->sa_smime && (sip->sip_request->rq_method == sip_method_invite || sip->sip_request->rq_method == sip_method_message)) { msg_prepare(orq->orq_request); if (sm_encode_message(smime, msg, sip, SM_ID_NULL) < 0) { outgoing_tport_error(sa, orq, NULL, orq->orq_request, su_errno()); return; } } } #endif orq->orq_prepared = 1; if (orq->orq_delayed) { SU_DEBUG_5(("nta: delayed sending %s (%u)\n", orq->orq_method_name, orq->orq_cseq->cs_seq)); outgoing_queue(orq->orq_agent->sa_out.delayed, orq); return; } outgoing_send(orq, 0); } /** Send a request */ static void outgoing_send(nta_outgoing_t *orq, int retransmit) { int err; tp_name_t const *tpn = orq->orq_tpn; msg_t *msg = orq->orq_request; nta_agent_t *agent = orq->orq_agent; tport_t *tp; int once = 0; su_time_t now = su_now(); tag_type_t tag = tag_skip; tag_value_t value = 0; struct sigcomp_compartment *cc; cc = NULL; /* tport can be NULL if we are just switching network */ if (orq->orq_tport == NULL) { outgoing_tport_error(agent, orq, NULL, orq->orq_request, ENETRESET); return; } if (orq->orq_user_tport && !tport_is_clear_to_send(orq->orq_tport)) { outgoing_tport_error(agent, orq, NULL, orq->orq_request, EPIPE); return; } if (!retransmit) orq->orq_sent = now; if (orq->orq_timestamp) { sip_t *sip = sip_object(msg); sip_timestamp_t *ts = sip_timestamp_format(msg_home(msg), "%lu.%06lu", now.tv_sec, now.tv_usec); if (ts) { if (sip->sip_timestamp) msg_header_remove(msg, (msg_pub_t *)sip, (msg_header_t *)sip->sip_timestamp); msg_header_insert(msg, (msg_pub_t *)sip, (msg_header_t *)ts); } } for (;;) { if (tpn->tpn_comp == NULL) { /* xyzzy */ } else if (orq->orq_cc) { cc = orq->orq_cc, orq->orq_cc = NULL; } else { cc = agent_compression_compartment(agent, orq->orq_tport, tpn, orq->orq_sigcomp_new); } if (orq->orq_try_udp_instead) tag = tptag_mtu, value = 65535; if (orq->orq_pending) { tport_release(orq->orq_tport, orq->orq_pending, orq->orq_request, NULL, orq, 0); orq->orq_pending = 0; } tp = tport_tsend(orq->orq_tport, msg, tpn, tag, value, IF_SIGCOMP_TPTAG_COMPARTMENT(cc) TAG_NEXT(orq->orq_tags)); if (tp) break; err = msg_errno(orq->orq_request); if (cc) nta_compartment_decref(&cc); if (orq->orq_user_tport) /* No retries */; /* RFC3261, 18.1.1 */ else if (err == EMSGSIZE && !orq->orq_try_tcp_instead) { if (su_casematch(tpn->tpn_proto, "udp") || su_casematch(tpn->tpn_proto, "*")) { outgoing_try_tcp_instead(orq); continue; } } else if (err == ECONNREFUSED && orq->orq_try_tcp_instead) { if (su_casematch(tpn->tpn_proto, "tcp") && msg_size(msg) <= 65535) { outgoing_try_udp_instead(orq, 0); continue; } } else if (err == EPIPE) { /* Connection was closed */ if (!once++) { orq->orq_retries++; continue; } } outgoing_tport_error(agent, orq, NULL, orq->orq_request, err); return; } agent->sa_stats->as_sent_msg++; agent->sa_stats->as_sent_request++; if (retransmit) agent->sa_stats->as_retry_request++; SU_DEBUG_5(("nta: %ssent %s (%u) to " TPN_FORMAT "\n", retransmit ? "re" : "", orq->orq_method_name, orq->orq_cseq->cs_seq, TPN_ARGS(tpn))); if (cc) { if (orq->orq_cc) nta_compartment_decref(&orq->orq_cc); } if (orq->orq_pending) { assert(orq->orq_tport); tport_release(orq->orq_tport, orq->orq_pending, orq->orq_request, NULL, orq, 0); orq->orq_pending = 0; } if (orq->orq_stateless) { outgoing_reply(orq, 202, NULL, 202); return; } if (orq->orq_method != sip_method_ack) { orq->orq_pending = tport_pend(tp, orq->orq_request, outgoing_tport_error, orq); if (orq->orq_pending < 0) orq->orq_pending = 0; } if (tp != orq->orq_tport) { tport_decref(&orq->orq_tport); orq->orq_tport = tport_ref(tp); } orq->orq_reliable = tport_is_reliable(tp); if (retransmit) return; outgoing_trying(orq); /* Timer B / F */ if (orq->orq_method == sip_method_ack) ; else if (!orq->orq_reliable) outgoing_set_timer(orq, agent->sa_t1); /* Timer A/E */ else if (orq->orq_try_tcp_instead && !tport_is_connected(tp)) outgoing_set_timer(orq, agent->sa_t4); /* Timer N3 */ } static void outgoing_try_tcp_instead(nta_outgoing_t *orq) { tport_t *tp; tp_name_t tpn[1]; assert(orq->orq_pending == 0); *tpn = *orq->orq_tpn; tpn->tpn_proto = "tcp"; orq->orq_try_tcp_instead = 1; tp = tport_by_name(orq->orq_agent->sa_tports, tpn); if (tp && tp != orq->orq_tport) { sip_t *sip = sip_object(orq->orq_request); msg_fragment_clear_chain((msg_header_t *)sip->sip_via); sip->sip_via->v_protocol = sip_transport_tcp; SU_DEBUG_5(("nta: %s (%u) too large for UDP, trying TCP\n", orq->orq_method_name, orq->orq_cseq->cs_seq)); orq->orq_tpn->tpn_proto = "tcp"; tport_decref(&orq->orq_tport); orq->orq_tport = tport_ref(tp); return; } /* No TCP - try again with UDP without SIP MTU limit */ tpn->tpn_proto = "udp"; orq->orq_try_udp_instead = 1; tp = tport_by_name(orq->orq_agent->sa_tports, tpn); if (tp && tp != orq->orq_tport) { SU_DEBUG_5(("nta: %s (%u) exceed normal UDP size limit\n", orq->orq_method_name, orq->orq_cseq->cs_seq)); tport_decref(&orq->orq_tport); orq->orq_tport = tport_ref(tp); } } static void outgoing_try_udp_instead(nta_outgoing_t *orq, int timeout) { tport_t *tp; tp_name_t tpn[1]; if (orq->orq_pending) { tport_release(orq->orq_tport, orq->orq_pending, orq->orq_request, NULL, orq, 0); orq->orq_pending = 0; } *tpn = *orq->orq_tpn; tpn->tpn_proto = "udp"; orq->orq_try_udp_instead = 1; tp = tport_by_name(orq->orq_agent->sa_tports, tpn); if (tp && tp != orq->orq_tport) { sip_t *sip = sip_object(orq->orq_request); msg_fragment_clear_chain((msg_header_t *)sip->sip_via); sip->sip_via->v_protocol = sip_transport_udp; SU_DEBUG_5(("nta: %s (%u) TCP %s, trying UDP\n", orq->orq_method_name, orq->orq_cseq->cs_seq, timeout ? "times out" : "refused")); orq->orq_tpn->tpn_proto = "udp"; tport_decref(&orq->orq_tport); orq->orq_tport = tport_ref(tp); } } /** @internal Report transport errors. */ void outgoing_tport_error(nta_agent_t *agent, nta_outgoing_t *orq, tport_t *tp, msg_t *msg, int error) { tp_name_t const *tpn = tp ? tport_name(tp) : orq->orq_tpn; if (orq->orq_pending) { assert(orq->orq_tport); tport_release(orq->orq_tport, orq->orq_pending, orq->orq_request, NULL, orq, 0); orq->orq_pending = 0; } if (error == EPIPE && orq->orq_retries++ == 0) { /* XXX - we should retry only if the transport is not newly created */ outgoing_print_tport_error(orq, 5, "retrying once after ", tpn, msg, error); outgoing_send(orq, 1); return; } else if (error == ECONNREFUSED && orq->orq_try_tcp_instead) { /* RFC3261, 18.1.1 */ if (su_casematch(tpn->tpn_proto, "tcp") && msg_size(msg) <= 65535) { outgoing_print_tport_error(orq, 5, "retrying with UDP after ", tpn, msg, error); outgoing_try_udp_instead(orq, 0); outgoing_remove(orq); /* Reset state - this is no resend! */ outgoing_send(orq, 0); /* Send */ return; } } if (outgoing_other_destinations(orq)) { outgoing_print_tport_error(orq, 5, "trying alternative server after ", tpn, msg, error); outgoing_try_another(orq); return; } outgoing_print_tport_error(orq, 3, "", tpn, msg, error); outgoing_reply(orq, SIP_503_SERVICE_UNAVAILABLE, 0); } static void outgoing_print_tport_error(nta_outgoing_t *orq, int level, char *todo, tp_name_t const *tpn, msg_t *msg, int error) { su_sockaddr_t const *su = msg_addr(msg); char addr[SU_ADDRSIZE]; su_llog(nta_log, level, "nta: %s (%u): %s%s (%u) with %s/[%s]:%u\n", orq->orq_method_name, orq->orq_cseq->cs_seq, todo, su_strerror(error), error, tpn->tpn_proto, su_inet_ntop(su->su_family, SU_ADDR(su), addr, sizeof(addr)), htons(su->su_port)); } /**@internal * Add features supported. */ static int outgoing_features(nta_agent_t *agent, nta_outgoing_t *orq, msg_t *msg, sip_t *sip, tagi_t *tags) { char const *supported[8]; int i; if (orq->orq_method != sip_method_invite) /* fast path for now */ return 0; supported[i = 0] = NULL; if (orq->orq_method == sip_method_invite) { int require_100rel = sip_has_feature(sip->sip_require, "100rel"); if (require_100rel) { orq->orq_must_100rel = 1; orq->orq_100rel = 1; } else if (sip_has_feature(sip->sip_supported, "100rel")) { orq->orq_100rel = 1; } else if (orq->orq_100rel) { supported[i++] = "100rel"; } } if (i) { supported[i] = NULL; if (sip->sip_supported) { su_home_t *home = msg_home(msg); return msg_list_append_items(home, sip->sip_supported, supported); } else { sip_supported_t s[1]; sip_supported_init(s); s->k_items = supported; return sip_add_dup(msg, sip, (sip_header_t *)s); } } return 0; } /**@internal * Insert outgoing request to agent hash table */ static void outgoing_insert(nta_agent_t *agent, nta_outgoing_t *orq) { if (outgoing_htable_is_full(agent->sa_outgoing)) outgoing_htable_resize(agent->sa_home, agent->sa_outgoing, 0); outgoing_htable_insert(agent->sa_outgoing, orq); orq->orq_inserted = 1; } /** @internal * Initialize a queue for outgoing transactions. */ static void outgoing_queue_init(outgoing_queue_t *queue, unsigned timeout) { memset(queue, 0, sizeof *queue); queue->q_tail = &queue->q_head; queue->q_timeout = timeout; } /** Change the timeout value of a queue */ static void outgoing_queue_adjust(nta_agent_t *sa, outgoing_queue_t *queue, unsigned timeout) { nta_outgoing_t *orq; uint32_t latest; if (timeout >= queue->q_timeout || !queue->q_head) { queue->q_timeout = timeout; return; } latest = set_timeout(sa, queue->q_timeout = timeout); for (orq = queue->q_head; orq; orq = orq->orq_next) { if (orq->orq_timeout == 0 || (int32_t)(orq->orq_timeout - latest) > 0) orq->orq_timeout = latest; } } /** @internal * Test if an outgoing transaction is in a queue. */ su_inline int outgoing_is_queued(nta_outgoing_t const *orq) { return orq && orq->orq_queue; } /** @internal * Insert an outgoing transaction into a queue. * * Insert a client transaction into a queue and set the corresponding * timeout at the same time. */ static void outgoing_queue(outgoing_queue_t *queue, nta_outgoing_t *orq) { if (orq->orq_queue == queue) { assert(queue->q_timeout == 0); return; } assert(!orq->orq_forked); if (outgoing_is_queued(orq)) outgoing_remove(orq); orq->orq_timeout = set_timeout(orq->orq_agent, queue->q_timeout); orq->orq_queue = queue; orq->orq_prev = queue->q_tail; *queue->q_tail = orq; queue->q_tail = &orq->orq_next; queue->q_length++; } /** @internal * Remove an outgoing transaction from a queue. */ su_inline void outgoing_remove(nta_outgoing_t *orq) { assert(outgoing_is_queued(orq)); assert(orq->orq_queue->q_length > 0); if ((*orq->orq_prev = orq->orq_next)) orq->orq_next->orq_prev = orq->orq_prev; else orq->orq_queue->q_tail = orq->orq_prev; orq->orq_queue->q_length--; orq->orq_next = NULL; orq->orq_prev = NULL; orq->orq_queue = NULL; orq->orq_timeout = 0; } /** Set retransmit timer (orq_retry). * * Set the retry timer (B/D) on the outgoing request (client transaction). */ su_inline void outgoing_set_timer(nta_outgoing_t *orq, uint32_t interval) { nta_outgoing_t **rq; assert(orq); if (interval == 0) { outgoing_reset_timer(orq); return; } if (orq->orq_rprev) { /* Remove transaction from retry dequeue, re-insert it later. */ if ((*orq->orq_rprev = orq->orq_rnext)) orq->orq_rnext->orq_rprev = orq->orq_rprev; if (orq->orq_agent->sa_out.re_t1 == &orq->orq_rnext) orq->orq_agent->sa_out.re_t1 = orq->orq_rprev; } else { orq->orq_agent->sa_out.re_length++; } orq->orq_retry = set_timeout(orq->orq_agent, orq->orq_interval = interval); /* Shortcut into queue at SIP T1 */ rq = orq->orq_agent->sa_out.re_t1; if (!(*rq) || (int32_t)((*rq)->orq_retry - orq->orq_retry) > 0) rq = &orq->orq_agent->sa_out.re_list; while (*rq && (int32_t)((*rq)->orq_retry - orq->orq_retry) <= 0) rq = &(*rq)->orq_rnext; if ((orq->orq_rnext = *rq)) orq->orq_rnext->orq_rprev = &orq->orq_rnext; *rq = orq; orq->orq_rprev = rq; if (interval == orq->orq_agent->sa_t1) orq->orq_agent->sa_out.re_t1 = rq; } static void outgoing_reset_timer(nta_outgoing_t *orq) { if (orq->orq_rprev) { if ((*orq->orq_rprev = orq->orq_rnext)) orq->orq_rnext->orq_rprev = orq->orq_rprev; if (orq->orq_agent->sa_out.re_t1 == &orq->orq_rnext) orq->orq_agent->sa_out.re_t1 = orq->orq_rprev; orq->orq_agent->sa_out.re_length--; } orq->orq_interval = 0, orq->orq_retry = 0; orq->orq_rnext = NULL, orq->orq_rprev = NULL; } /** @internal * Free resources associated with the request. */ static void outgoing_free(nta_outgoing_t *orq) { SU_DEBUG_9(("nta: outgoing_free(%p)\n", (void *)orq)); assert(orq->orq_forks == NULL && orq->orq_forking == NULL); outgoing_cut_off(orq); outgoing_reclaim(orq); } /** Remove outgoing request from hash tables */ su_inline void outgoing_cut_off(nta_outgoing_t *orq) { nta_agent_t *agent = orq->orq_agent; if (orq->orq_default) agent->sa_default_outgoing = NULL; if (orq->orq_inserted) outgoing_htable_remove(agent->sa_outgoing, orq), orq->orq_inserted = 0; if (outgoing_is_queued(orq)) outgoing_remove(orq); #if 0 if (orq->orq_forked) outgoing_remove_fork(orq); #endif outgoing_reset_timer(orq); if (orq->orq_pending) { tport_release(orq->orq_tport, orq->orq_pending, orq->orq_request, NULL, orq, 0); } orq->orq_pending = 0; if (orq->orq_cc) nta_compartment_decref(&orq->orq_cc); if (orq->orq_tport) tport_decref(&orq->orq_tport); } /** Reclaim outgoing request */ su_inline void outgoing_reclaim(nta_outgoing_t *orq) { if (orq->orq_status2b) *orq->orq_status2b = -1; if (orq->orq_request) msg_destroy(orq->orq_request), orq->orq_request = NULL; if (orq->orq_response) msg_destroy(orq->orq_response), orq->orq_response = NULL; #if HAVE_SOFIA_SRESOLV if (orq->orq_resolver) outgoing_destroy_resolver(orq); #endif su_free(orq->orq_agent->sa_home, orq); } /** Queue request to be freed */ su_inline void outgoing_free_queue(outgoing_queue_t *q, nta_outgoing_t *orq) { outgoing_cut_off(orq); outgoing_queue(q, orq); } /** Reclaim memory used by queue of requests */ static void outgoing_reclaim_queued(su_root_magic_t *rm, su_msg_r msg, union sm_arg_u *u) { outgoing_queue_t *q = u->a_outgoing_queue; nta_outgoing_t *orq, *orq_next; SU_DEBUG_9(("outgoing_reclaim_all(%p, %p, %p)\n", (void *)rm, (void *)msg, (void *)u)); for (orq = q->q_head; orq; orq = orq_next) { orq_next = orq->orq_next; outgoing_reclaim(orq); } } /** @internal Default callback for request */ int outgoing_default_cb(nta_outgoing_magic_t *magic, nta_outgoing_t *orq, sip_t const *sip) { if (sip == NULL || sip->sip_status->st_status >= 200) outgoing_destroy(orq); return 0; } /** @internal Destroy an outgoing transaction */ void outgoing_destroy(nta_outgoing_t *orq) { if (orq->orq_terminated || orq->orq_default) { if (!orq->orq_forking && !orq->orq_forks) { outgoing_free(orq); return; } } /* Application is expected to handle 200 OK statelessly => kill transaction immediately */ else if (orq->orq_method == sip_method_invite && !orq->orq_completed /* (unless transaction has been canceled) */ && !orq->orq_canceled /* or it has been forked */ && !orq->orq_forking && !orq->orq_forks) { orq->orq_destroyed = 1; outgoing_terminate(orq); return; } orq->orq_destroyed = 1; orq->orq_callback = outgoing_default_cb; orq->orq_magic = NULL; } /** @internal Outgoing transaction timer routine. * */ static void _nta_outgoing_timer(nta_agent_t *sa) { uint32_t now = sa->sa_millisec; nta_outgoing_t *orq; outgoing_queue_t rq[1]; size_t retransmitted = 0, terminated = 0, timeout = 0, destroyed; size_t total = sa->sa_outgoing->oht_used; size_t trying = sa->sa_out.re_length; size_t pending = sa->sa_out.trying->q_length + sa->sa_out.inv_calling->q_length; size_t completed = sa->sa_out.completed->q_length + sa->sa_out.inv_completed->q_length; outgoing_queue_init(sa->sa_out.free = rq, 0); while ((orq = sa->sa_out.re_list)) { if ((int32_t)(orq->orq_retry - now) > 0) break; if (retransmitted >= timer_max_retransmit) break; if (orq->orq_reliable) { outgoing_reset_timer(orq); if (!tport_is_connected(orq->orq_tport)) { /* * Timer N3: try to use UDP if trying to send via TCP * but no connection is established within SIP T4 */ SU_DEBUG_5(("nta: timer %s fired, %s %s (%u)\n", "N3", "try UDP instead for", orq->orq_method_name, orq->orq_cseq->cs_seq)); outgoing_try_udp_instead(orq, 1); outgoing_remove(orq); /* Reset state - this is no resend! */ outgoing_send(orq, 0); /* Send */ } continue; } assert(!orq->orq_reliable && orq->orq_interval != 0); SU_DEBUG_5(("nta: timer %s fired, %s %s (%u)\n", orq->orq_method == sip_method_invite ? "A" : "E", "retransmit", orq->orq_method_name, orq->orq_cseq->cs_seq)); outgoing_retransmit(orq); if (orq->orq_method == sip_method_invite || 2U * orq->orq_interval < sa->sa_t2) outgoing_set_timer(orq, 2U * orq->orq_interval); else outgoing_set_timer(orq, sa->sa_t2); if (++retransmitted % 5 == 0) su_root_yield(sa->sa_root); /* Handle received packets */ } terminated = outgoing_timer_dk(sa->sa_out.inv_completed, "D", now) + outgoing_timer_dk(sa->sa_out.completed, "K", now); timeout = outgoing_timer_bf(sa->sa_out.inv_calling, "B", now) + outgoing_timer_c(sa->sa_out.inv_proceeding, "C", now) + outgoing_timer_bf(sa->sa_out.trying, "F", now); destroyed = outgoing_mass_destroy(sa, rq); sa->sa_out.free = NULL; if (retransmitted || timeout || terminated || destroyed) { SU_DEBUG_5(("nta_outgoing_timer: " MOD_ZU"/"MOD_ZU" resent, " MOD_ZU"/"MOD_ZU" tout, " MOD_ZU"/"MOD_ZU" term, " MOD_ZU"/"MOD_ZU" free\n", retransmitted, trying, timeout, pending, terminated, completed, destroyed, total)); } } /** @internal Retransmit the outgoing request. */ void outgoing_retransmit(nta_outgoing_t *orq) { if (orq->orq_prepared && !orq->orq_delayed) { orq->orq_retries++; if (orq->orq_retries >= 4 && orq->orq_cc) { orq->orq_tpn->tpn_comp = NULL; if (orq->orq_retries == 4) { agent_close_compressor(orq->orq_agent, orq->orq_cc); nta_compartment_decref(&orq->orq_cc); } } outgoing_send(orq, 1); } } /** Trying a client transaction. */ static void outgoing_trying(nta_outgoing_t *orq) { if (orq->orq_forked) ; else if (orq->orq_method == sip_method_invite) outgoing_queue(orq->orq_agent->sa_out.inv_calling, orq); else outgoing_queue(orq->orq_agent->sa_out.trying, orq); } /** Handle timers B and F */ static size_t outgoing_timer_bf(outgoing_queue_t *q, char const *timer, uint32_t now) { nta_outgoing_t *orq; size_t timeout = 0; while ((orq = q->q_head)) { if ((int32_t)(orq->orq_timeout - now) > 0 || timeout >= timer_max_timeout) break; timeout++; SU_DEBUG_5(("nta: timer %s fired, %s %s (%u)\n", timer, orq->orq_method != sip_method_ack ? "timeout" : "terminating", orq->orq_method_name, orq->orq_cseq->cs_seq)); if (orq->orq_method != sip_method_ack) outgoing_timeout(orq, now); else outgoing_terminate(orq); assert(q->q_head != orq || (int32_t)(orq->orq_timeout - now) > 0); } return timeout; } /** Handle timer C */ static size_t outgoing_timer_c(outgoing_queue_t *q, char const *timer, uint32_t now) { nta_outgoing_t *orq; size_t timeout = 0; if (q->q_timeout == 0) return 0; while ((orq = q->q_head)) { if ((int32_t)(orq->orq_timeout - now) > 0 || timeout >= timer_max_timeout) break; timeout++; SU_DEBUG_5(("nta: timer %s fired, %s %s (%u)\n", timer, "CANCEL and timeout", orq->orq_method_name, orq->orq_cseq->cs_seq)); /* * If the client transaction has received a provisional response, the * proxy MUST generate a CANCEL request matching that transaction. */ nta_outgoing_tcancel(orq, NULL, NULL, TAG_NULL()); } return timeout; } /** @internal Signal transaction timeout to the application. */ void outgoing_timeout(nta_outgoing_t *orq, uint32_t now) { nta_outgoing_t *cancel = NULL; if (orq->orq_status || orq->orq_canceled) ; else if (outgoing_other_destinations(orq)) { SU_DEBUG_5(("%s(%p): %s\n", "nta", (void *)orq, "try next after timeout")); outgoing_try_another(orq); return; } cancel = orq->orq_cancel, orq->orq_cancel = NULL; orq->orq_agent->sa_stats->as_tout_request++; outgoing_reply(orq, SIP_408_REQUEST_TIMEOUT, 0); if (cancel) outgoing_timeout(cancel, now); } /** Complete a client transaction. * * @return True if transaction was free()d. */ static int outgoing_complete(nta_outgoing_t *orq) { orq->orq_completed = 1; outgoing_reset_timer(orq); /* Timer A / Timer E */ if (orq->orq_stateless) return outgoing_terminate(orq); if (orq->orq_forked) { outgoing_remove_fork(orq); return outgoing_terminate(orq); } if (orq->orq_reliable) { if (orq->orq_method != sip_method_invite || !orq->orq_uas) return outgoing_terminate(orq); } outgoing_cancel_resolver(orq); if (orq->orq_method == sip_method_invite) { if (orq->orq_queue != orq->orq_agent->sa_out.inv_completed) outgoing_queue(orq->orq_agent->sa_out.inv_completed, orq); /* Timer D */ } else { outgoing_queue(orq->orq_agent->sa_out.completed, orq); /* Timer K */ } return 0; } /** Handle timers D and K */ static size_t outgoing_timer_dk(outgoing_queue_t *q, char const *timer, uint32_t now) { nta_outgoing_t *orq; size_t terminated = 0; while ((orq = q->q_head)) { if ((int32_t)(orq->orq_timeout - now) > 0 || terminated >= timer_max_terminate) break; terminated++; SU_DEBUG_5(("nta: timer %s fired, %s %s (%u)\n", timer, "terminate", orq->orq_method_name, orq->orq_cseq->cs_seq)); if (orq->orq_method == sip_method_invite) outgoing_terminate_invite(orq); else outgoing_terminate(orq); } return terminated; } /** Terminate an INVITE client transaction. */ static void outgoing_terminate_invite(nta_outgoing_t *original) { nta_outgoing_t *orq = original; while (original->orq_forks) { orq = original->orq_forks; original->orq_forks = orq->orq_forks; assert(orq->orq_forking == original); SU_DEBUG_5(("nta: timer %s fired, %s %s (%u);tag=%s\n", "D", "terminate", orq->orq_method_name, orq->orq_cseq->cs_seq, orq->orq_tag)); orq->orq_forking = NULL, orq->orq_forks = NULL, orq->orq_forked = 0; if (outgoing_terminate(orq)) continue; if (orq->orq_status < 200) { /* Fork has timed out */ orq->orq_agent->sa_stats->as_tout_request++; outgoing_reply(orq, SIP_408_REQUEST_TIMEOUT, 0); } } if (outgoing_terminate(orq = original)) return; if (orq->orq_status < 200) { /* Original INVITE has timed out */ orq->orq_agent->sa_stats->as_tout_request++; outgoing_reply(orq, SIP_408_REQUEST_TIMEOUT, 0); } } static void outgoing_remove_fork(nta_outgoing_t *orq) { nta_outgoing_t **slot; for (slot = &orq->orq_forking->orq_forks; *slot; slot = &(*slot)->orq_forks) { if (orq == *slot) { *slot = orq->orq_forks; orq->orq_forks = NULL; orq->orq_forking = NULL; orq->orq_forked = 0; } } assert(orq == NULL); } /** Terminate a client transaction. */ static int outgoing_terminate(nta_outgoing_t *orq) { orq->orq_terminated = 1; outgoing_cancel_resolver(orq); if (!orq->orq_destroyed) { outgoing_queue(orq->orq_agent->sa_out.terminated, orq); return 0; } else if (orq->orq_agent->sa_out.free) { outgoing_free_queue(orq->orq_agent->sa_out.free, orq); return 1; } else { outgoing_free(orq); return 1; } } /** Mass destroy client transactions */ static size_t outgoing_mass_destroy(nta_agent_t *sa, outgoing_queue_t *q) { size_t destroyed = q->q_length; if (destroyed > 2 && *sa->sa_terminator) { su_msg_r m = SU_MSG_R_INIT; if (su_msg_create(m, su_clone_task(sa->sa_terminator), su_root_task(sa->sa_root), outgoing_reclaim_queued, sizeof(outgoing_queue_t)) == SU_SUCCESS) { outgoing_queue_t *mq = su_msg_data(m)->a_outgoing_queue; *mq = *q; if (su_msg_send(m) == SU_SUCCESS) q->q_length = 0; } } if (q->q_length) outgoing_reclaim_queued(NULL, NULL, (void*)q); return destroyed; } /** Find an outgoing request corresponging to a message and @Via line. * * Return an outgoing request object based on a message and the @Via line * given as argument. This function is used when doing loop checking: if we * have sent the request and it has been routed back to us. * * @param agent * @param msg * @param sip * @param v */ nta_outgoing_t *nta_outgoing_find(nta_agent_t const *agent, msg_t const *msg, sip_t const *sip, sip_via_t const *v) { if (agent == NULL || msg == NULL || sip == NULL || v == NULL) { su_seterrno(EFAULT); return NULL; } return outgoing_find(agent, msg, sip, v); } /**@internal * * Find an outgoing request corresponging to a message and @Via line. * */ nta_outgoing_t *outgoing_find(nta_agent_t const *sa, msg_t const *msg, sip_t const *sip, sip_via_t const *v) { nta_outgoing_t **oo, *orq; outgoing_htable_t const *oht = sa->sa_outgoing; sip_cseq_t const *cseq = sip->sip_cseq; sip_call_id_t const *i = sip->sip_call_id; hash_value_t hash; sip_method_t method, method2; unsigned short status = sip->sip_status ? sip->sip_status->st_status : 0; if (cseq == NULL) return NULL; hash = NTA_HASH(i, cseq->cs_seq); method = cseq->cs_method; /* Get original invite when ACKing */ if (sip->sip_request && method == sip_method_ack && v == NULL) method = sip_method_invite, method2 = sip_method_invalid; else if (sa->sa_is_a_uas && 200 <= status && status < 300 && method == sip_method_invite) method2 = sip_method_ack; else method2 = method; for (oo = outgoing_htable_hash(oht, hash); (orq = *oo); oo = outgoing_htable_next(oht, oo)) { if (orq->orq_stateless) continue; /* Accept terminated transactions when looking for original INVITE */ if (orq->orq_terminated && method2 != sip_method_invalid) continue; if (hash != orq->orq_hash) continue; if (orq->orq_call_id->i_hash != i->i_hash || strcmp(orq->orq_call_id->i_id, i->i_id)) continue; if (orq->orq_cseq->cs_seq != cseq->cs_seq) continue; if (method == sip_method_unknown && strcmp(orq->orq_cseq->cs_method_name, cseq->cs_method_name)) continue; if (orq->orq_method != method && orq->orq_method != method2) continue; if (su_strcasecmp(orq->orq_from->a_tag, sip->sip_from->a_tag)) continue; if (orq->orq_to->a_tag && su_strcasecmp(orq->orq_to->a_tag, sip->sip_to->a_tag)) continue; if (orq->orq_method == sip_method_ack && 300 <= status) continue; if (v && !su_casematch(orq->orq_branch + strlen("branch="), v->v_branch)) continue; break; /* match */ } return orq; } /** Process a response message. */ int outgoing_recv(nta_outgoing_t *_orq, int status, msg_t *msg, sip_t *sip) { nta_outgoing_t *orq = _orq->orq_forking ? _orq->orq_forking : _orq; nta_agent_t *sa = orq->orq_agent; int internal = sip == NULL || (sip->sip_flags & NTA_INTERNAL_MSG) != 0; assert(!internal || status >= 300); assert(orq == _orq || orq->orq_method == sip_method_invite); if (status < 100) status = 100; if (!internal && orq->orq_delay == UINT_MAX) outgoing_estimate_delay(orq, sip); if (orq->orq_cc) agent_accept_compressed(orq->orq_agent, msg, orq->orq_cc); if (orq->orq_cancel) { nta_outgoing_t *cancel; cancel = orq->orq_cancel; orq->orq_cancel = NULL; cancel->orq_delayed = 0; if (status < 200) { outgoing_send(cancel, 0); if (outgoing_complete(orq)) return 0; } else { outgoing_reply(cancel, SIP_481_NO_TRANSACTION, 0); } } if (orq->orq_pending) { tport_release(orq->orq_tport, orq->orq_pending, orq->orq_request, msg, orq, status < 200); if (status >= 200) orq->orq_pending = 0; } /* The state machines */ if (orq->orq_method == sip_method_invite) { nta_outgoing_t *original = orq; orq = _orq; if (orq->orq_destroyed && 200 <= status && status < 300) { if (orq->orq_uas && su_strcasecmp(sip->sip_to->a_tag, orq->orq_tag) != 0) { /* Orphan 200 Ok to INVITE. ACK and BYE it */ SU_DEBUG_5(("nta: Orphan 200 Ok send ACK&BYE\n")); return nta_msg_ackbye(sa, msg); } return -1; /* Proxy statelessly (RFC3261 section 16.11) */ } outgoing_reset_timer(original); /* Retransmission */ if (status < 200) { if (original->orq_status < 200) original->orq_status = status; if (orq->orq_status < 200) orq->orq_status = status; if (original->orq_queue == sa->sa_out.inv_calling) { outgoing_queue(sa->sa_out.inv_proceeding, original); } else if (original->orq_queue == sa->sa_out.inv_proceeding) { if (sa->sa_out.inv_proceeding->q_timeout) { outgoing_remove(original); outgoing_queue(sa->sa_out.inv_proceeding, original); } } /* Handle 100rel */ if (sip && sip->sip_rseq) { if (outgoing_recv_reliable(orq, msg, sip) < 0) { msg_destroy(msg); return 0; } } } else { /* Final response */ if (status >= 300 && !internal) outgoing_ack(original, sip); if (!original->orq_completed) { if (outgoing_complete(original)) return 0; if (orq->orq_uas && sip && orq == original) { /* * We silently discard duplicate final responses to INVITE below * with outgoing_duplicate() */ su_home_t *home = msg_home(orq->orq_request); orq->orq_tag = su_strdup(home, sip->sip_to->a_tag); } } /* Retransmission or response from another fork */ else if (orq->orq_status >= 200) { /* Once 2xx has been received, non-2xx will not be forwarded */ if (status >= 300) return outgoing_duplicate(orq, msg, sip); if (orq->orq_uas) { if (su_strcasecmp(sip->sip_to->a_tag, orq->orq_tag) == 0) /* Catch retransmission */ return outgoing_duplicate(orq, msg, sip); /* Orphan 200 Ok to INVITE. ACK and BYE it */ SU_DEBUG_5(("nta: Orphan 200 Ok send ACK&BYE")); return nta_msg_ackbye(sa, msg); } } orq->orq_status = status; } } else if (orq->orq_method != sip_method_ack) { /* Non-INVITE */ if (orq->orq_queue == sa->sa_out.trying || orq->orq_queue == sa->sa_out.resolving) { if (orq->orq_status >= 200) { /* hacked by freeswitch: this is being hit by options 404 status with 404 in orq->orq_status and orq_destroyed = 1, orq_completed = 1 */ /* assert(orq->orq_status < 200); */ msg_destroy(msg); return 0; } if (status < 200) { /* @RFC3261 17.1.2.1: * retransmissions continue for unreliable transports, * but at an interval of T2. * * @RFC4321 1.2: * Note that Timer E is not altered during the transition * to Proceeding. */ if (!orq->orq_reliable) orq->orq_interval = sa->sa_t2; #if notyet /* Destination has been already flushed */ if (orq->orq_queue == sa->sa_out.resolving) { /* A response from (previously resolved) destination? */ outgoing_cancel_resolver(orq); outgoing_trying(orq); } #endif } else if (outgoing_complete(orq)) { msg_destroy(msg); /* Transaction was terminated and destroyed */ return 0; } else { if (orq->orq_sigcomp_zap && orq->orq_tport && orq->orq_cc) agent_zap_compressor(orq->orq_agent, orq->orq_cc); } } else { /* Already completed or terminated */ assert(orq->orq_queue == sa->sa_out.completed || orq->orq_queue == sa->sa_out.terminated); assert(orq->orq_status >= 200); return outgoing_duplicate(orq, msg, sip); } orq->orq_status = status; } else { /* ACK */ if (sip && (sip->sip_flags & NTA_INTERNAL_MSG) == 0) /* Received re-transmitted final reply to INVITE, retransmit ACK */ outgoing_retransmit(orq); msg_destroy(msg); return 0; } if (100 >= status + orq->orq_pass_100) { msg_destroy(msg); return 0; } if (orq->orq_destroyed) { msg_destroy(msg); return 0; } if (orq->orq_response) msg_destroy(orq->orq_response); orq->orq_response = msg; /* Call callback */ orq->orq_callback(orq->orq_magic, orq, sip); return 0; } static void outgoing_default_recv(nta_outgoing_t *orq, int status, msg_t *msg, sip_t *sip) { assert(sip->sip_cseq); orq->orq_status = status; orq->orq_response = msg; orq->orq_callback(orq->orq_magic, orq, sip); orq->orq_response = NULL; orq->orq_status = 0; msg_destroy(msg); } static void outgoing_estimate_delay(nta_outgoing_t *orq, sip_t *sip) { su_time_t now = su_now(); double diff = 1000 * su_time_diff(now, orq->orq_sent); if (orq->orq_timestamp && sip->sip_timestamp) { double diff2, delay = 0.0; su_time_t timestamp = { 0, 0 }; char const *bad; sscanf(sip->sip_timestamp->ts_stamp, "%lu.%lu", &timestamp.tv_sec, &timestamp.tv_usec); diff2 = 1000 * su_time_diff(now, timestamp); if (diff2 < 0) bad = "negative"; else if (diff2 > diff + 1e-3) bad = "too large"; else { if (sip->sip_timestamp->ts_delay) sscanf(sip->sip_timestamp->ts_delay, "%lg", &delay); if (1000 * delay <= diff2) { diff = diff2 - 1000 * delay; orq->orq_delay = (unsigned)diff; SU_DEBUG_7(("nta_outgoing: RTT is %g ms, now is %lu.%06lu, " "Timestamp was %s %s\n", diff, now.tv_sec, now.tv_usec, sip->sip_timestamp->ts_stamp, sip->sip_timestamp->ts_delay ? sip->sip_timestamp->ts_delay : "")); return; } bad = "delay"; } SU_DEBUG_3(("nta_outgoing: %s Timestamp %lu.%06lu %g " "(sent %lu.%06lu, now is %lu.%06lu)\n", bad, timestamp.tv_sec, timestamp.tv_usec, delay, orq->orq_sent.tv_sec, orq->orq_sent.tv_usec, now.tv_sec, now.tv_usec)); } if (diff >= 0 && diff < (double)UINT_MAX) { orq->orq_delay = (unsigned)diff; SU_DEBUG_7(("nta_outgoing: RTT is %g ms\n", diff)); } } /**@typedef nta_response_f * * Callback for replies to outgoing requests. * * This is a callback function invoked by NTA when it has received a new * reply to an outgoing request. * * @param magic request context * @param request request handle * @param sip received status message * * @return * This callback function should return always 0. * */ /** Process duplicate responses */ static int outgoing_duplicate(nta_outgoing_t *orq, msg_t *msg, sip_t *sip) { sip_via_t *v; if (sip && (sip->sip_flags & NTA_INTERNAL_MSG) == 0) { v = sip->sip_via; SU_DEBUG_5(("nta: %u %s is duplicate response to %d %s\n", sip->sip_status->st_status, sip->sip_status->st_phrase, orq->orq_cseq->cs_seq, orq->orq_cseq->cs_method_name)); if (v) SU_DEBUG_5(("\tVia: %s %s%s%s%s%s%s%s%s%s\n", v->v_protocol, v->v_host, SIP_STRLOG(":", v->v_port), SIP_STRLOG(" ;received=", v->v_received), SIP_STRLOG(" ;maddr=", v->v_maddr), SIP_STRLOG(" ;branch=", v->v_branch))); } msg_destroy(msg); return 0; } /** @internal ACK to a final response (300..699). * These messages are ACK'ed via the original URL (and tport) */ void outgoing_ack(nta_outgoing_t *orq, sip_t *sip) { msg_t *ackmsg; assert(orq); /* Do not ack internally generated messages... */ if (sip == NULL || sip->sip_flags & NTA_INTERNAL_MSG) return; assert(sip); assert(sip->sip_status); assert(sip->sip_status->st_status >= 300); assert(orq->orq_tport); ackmsg = outgoing_ackmsg(orq, SIP_METHOD_ACK, SIPTAG_TO(sip->sip_to), TAG_END()); if (!ackmsg) return; if (!outgoing_create(orq->orq_agent, NULL, NULL, NULL, orq->orq_tpn, ackmsg, NTATAG_BRANCH_KEY(sip->sip_via->v_branch), NTATAG_USER_VIA(1), NTATAG_STATELESS(1), TAG_END())) msg_destroy(ackmsg); } /** Generate messages for hop-by-hop ACK or CANCEL. */ msg_t *outgoing_ackmsg(nta_outgoing_t *orq, sip_method_t m, char const *mname, tag_type_t tag, tag_value_t value, ...) { msg_t *msg = nta_msg_create(orq->orq_agent, 0); su_home_t *home = msg_home(msg); sip_t *sip = sip_object(msg); sip_t *old = sip_object(orq->orq_request); sip_via_t via[1]; if (!sip) return NULL; if (tag) { ta_list ta; ta_start(ta, tag, value); sip_add_tl(msg, sip, ta_tags(ta)); /* Bug sf.net # 173323: * Ensure that request-URI, topmost Via, From, To, Call-ID, CSeq, * Max-Forward, Route, Accept-Contact, Reject-Contact and * Request-Disposition are copied from original request */ if (sip->sip_from) sip_header_remove(msg, sip, (void *)sip->sip_from); if (sip->sip_to && m != sip_method_ack) sip_header_remove(msg, sip, (void *)sip->sip_to); if (sip->sip_call_id) sip_header_remove(msg, sip, (void *)sip->sip_call_id); while (sip->sip_route) sip_header_remove(msg, sip, (void *)sip->sip_route); while (sip->sip_accept_contact) sip_header_remove(msg, sip, (void *)sip->sip_accept_contact); while (sip->sip_reject_contact) sip_header_remove(msg, sip, (void *)sip->sip_reject_contact); if (sip->sip_request_disposition) sip_header_remove(msg, sip, (void *)sip->sip_request_disposition); while (sip->sip_via) sip_header_remove(msg, sip, (void *)sip->sip_via); if (sip->sip_max_forwards) sip_header_remove(msg, sip, (void *)sip->sip_max_forwards); ta_end(ta); } sip->sip_request = sip_request_create(home, m, mname, (url_string_t *)orq->orq_url, NULL); if (sip->sip_to == NULL) sip_add_dup(msg, sip, (sip_header_t *)old->sip_to); sip_add_dup(msg, sip, (sip_header_t *)old->sip_from); sip_add_dup(msg, sip, (sip_header_t *)old->sip_call_id); sip_add_dup(msg, sip, (sip_header_t *)old->sip_route); /* @RFC3841. Bug #1326727. */ sip_add_dup(msg, sip, (sip_header_t *)old->sip_accept_contact); sip_add_dup(msg, sip, (sip_header_t *)old->sip_reject_contact); sip_add_dup(msg, sip, (sip_header_t *)old->sip_request_disposition); sip_add_dup(msg, sip, (sip_header_t *)old->sip_max_forwards); if (old->sip_via) { /* Add only the topmost Via header */ *via = *old->sip_via; via->v_next = NULL; sip_add_dup(msg, sip, (sip_header_t *)via); } sip->sip_cseq = sip_cseq_create(home, old->sip_cseq->cs_seq, m, mname); if (sip->sip_request && sip->sip_to && sip->sip_from && sip->sip_call_id && (!old->sip_route || sip->sip_route) && sip->sip_cseq) return msg; msg_destroy(msg); return NULL; } static void outgoing_delayed_recv(su_root_magic_t *rm, su_msg_r msg, union sm_arg_u *u); /** Respond internally to a transaction. */ int outgoing_reply(nta_outgoing_t *orq, int status, char const *phrase, int delayed) { nta_agent_t *agent = orq->orq_agent; msg_t *msg = NULL; sip_t *sip = NULL; assert(status == 202 || status >= 400); if (orq->orq_pending) tport_release(orq->orq_tport, orq->orq_pending, orq->orq_request, NULL, orq, 0); orq->orq_pending = 0; orq->orq_delayed = 0; if (orq->orq_method == sip_method_ack) { if (status != delayed) SU_DEBUG_3(("nta(%p): responding %u %s to ACK!\n", (void *)orq, status, phrase)); orq->orq_status = status; if (orq->orq_queue == NULL) outgoing_trying(orq); /* Timer F */ return 0; } if (orq->orq_destroyed) { if (orq->orq_status < 200) orq->orq_status = status; outgoing_complete(orq); /* Timer D / Timer K */ return 0; } if (orq->orq_stateless) ; else if (orq->orq_queue == NULL || orq->orq_queue == orq->orq_agent->sa_out.resolving || orq->orq_queue == orq->orq_agent->sa_out.delayed) outgoing_trying(orq); /** Insert a dummy Via header */ if (!orq->orq_prepared) { tport_t *tp = tport_primaries(orq->orq_agent->sa_tports); outgoing_insert_via(orq, agent_tport_via(tp)); } /* Create response message, if needed */ if (!orq->orq_stateless && !(orq->orq_callback == outgoing_default_cb) && !(status == 408 && orq->orq_method != sip_method_invite && !orq->orq_agent->sa_timeout_408)) { char const *to_tag; msg = nta_msg_create(agent, NTA_INTERNAL_MSG); if (complete_response(msg, status, phrase, orq->orq_request) < 0) { assert(!"complete message"); return -1; } sip = sip_object(msg); assert(sip->sip_flags & NTA_INTERNAL_MSG); to_tag = nta_agent_newtag(msg_home(msg), "tag=%s", agent); if (status > 100 && sip->sip_to && !sip->sip_to->a_tag && sip->sip_cseq->cs_method != sip_method_cancel && sip_to_tag(msg_home(msg), sip->sip_to, to_tag) < 0) { assert(!"adding tag"); return -1; } if (status > 400 && agent->sa_blacklist) { sip_retry_after_t af[1]; sip_retry_after_init(af)->af_delta = agent->sa_blacklist; sip_add_dup(msg, sip, (sip_header_t *)af); } } if (orq->orq_inserted && !delayed) { outgoing_recv(orq, status, msg, sip); return 0; } else if (orq->orq_stateless && orq->orq_callback == outgoing_default_cb) { /* Xyzzy */ orq->orq_status = status; outgoing_complete(orq); } else { /* * The thread creating outgoing transaction must return to application * before transaction callback can be invoked. Therefore processing an * internally generated response message must be delayed until * transaction creation is completed. * * The internally generated message is transmitted using su_msg_send() * and it is delivered back to NTA when the application next time * executes the su_root_t event loop. */ nta_agent_t *agent = orq->orq_agent; su_root_t *root = agent->sa_root; su_msg_r su_msg = SU_MSG_R_INIT; if (su_msg_create(su_msg, su_root_task(root), su_root_task(root), outgoing_delayed_recv, sizeof(struct outgoing_recv_s)) == SU_SUCCESS) { struct outgoing_recv_s *a = su_msg_data(su_msg)->a_outgoing_recv; a->orq = orq; a->msg = msg; a->sip = sip; a->status = status; orq->orq_status2b = &a->status; if (su_msg_send(su_msg) == SU_SUCCESS) { return 0; } } } if (msg) msg_destroy(msg); return -1; } static void outgoing_delayed_recv(su_root_magic_t *rm, su_msg_r msg, union sm_arg_u *u) { struct outgoing_recv_s *a = u->a_outgoing_recv; if (a->status > 0) { a->orq->orq_status2b = 0; if (outgoing_recv(a->orq, a->status, a->msg, a->sip) >= 0) return; } msg_destroy(a->msg); } /* ====================================================================== */ /* 9) Resolving (SIP) URL */ #if HAVE_SOFIA_SRESOLV struct sipdns_query; /** DNS resolving for (SIP) URLs */ struct sipdns_resolver { tp_name_t sr_tpn[1]; /**< Copy of original transport name */ sres_query_t *sr_query; /**< Current DNS Query */ char const *sr_target; /**< Target for current query */ struct sipdns_query *sr_current; /**< Current query (with results) */ char **sr_results; /**< A/AAAA results to be used */ struct sipdns_query *sr_head; /**< List of intermediate results */ struct sipdns_query **sr_tail; /**< End of intermediate result list */ struct sipdns_query *sr_done; /**< Completed intermediate results */ struct sipdns_tport const *sr_tport; /**< Selected transport */ /** Transports to consider for this request */ struct sipdns_tport const *sr_tports[SIPDNS_TRANSPORTS + 1]; uint16_t sr_a_aaaa1, sr_a_aaaa2; /**< Order of A and/or AAAA queries. */ unsigned sr_use_naptr:1, sr_use_srv:1, sr_use_a_aaaa:1; }; /** Intermediate queries */ struct sipdns_query { struct sipdns_query *sq_next; char const *sq_proto; char const *sq_domain; char sq_port[6]; /* port number */ uint16_t sq_otype; /* origin type of query data (0 means request) */ uint16_t sq_type; /* query type */ uint16_t sq_priority; /* priority or preference */ uint16_t sq_weight; /* preference or weight */ uint16_t sq_grayish; /* candidate for graylisting */ }; static int outgoing_resolve_next(nta_outgoing_t *orq); static int outgoing_resolving(nta_outgoing_t *orq); static int outgoing_resolving_error(nta_outgoing_t *, int status, char const *phrase); static void outgoing_graylist(nta_outgoing_t *orq, struct sipdns_query *sq); static int outgoing_query_naptr(nta_outgoing_t *orq, char const *domain); static void outgoing_answer_naptr(sres_context_t *orq, sres_query_t *q, sres_record_t *answers[]); struct sipdns_tport const *outgoing_naptr_tport(nta_outgoing_t *orq, sres_record_t *answers[]); static int outgoing_make_srv_query(nta_outgoing_t *orq); static int outgoing_make_a_aaaa_query(nta_outgoing_t *orq); static void outgoing_query_all(nta_outgoing_t *orq); static int outgoing_query_srv(nta_outgoing_t *orq, struct sipdns_query *); static void outgoing_answer_srv(sres_context_t *orq, sres_query_t *q, sres_record_t *answers[]); #if SU_HAVE_IN6 static int outgoing_query_aaaa(nta_outgoing_t *orq, struct sipdns_query *); static void outgoing_answer_aaaa(sres_context_t *orq, sres_query_t *q, sres_record_t *answers[]); #endif static int outgoing_query_a(nta_outgoing_t *orq, struct sipdns_query *); static void outgoing_answer_a(sres_context_t *orq, sres_query_t *q, sres_record_t *answers[]); static void outgoing_query_results(nta_outgoing_t *orq, struct sipdns_query *sq, char *results[], size_t rlen); #define SIPDNS_503_ERROR 503, "DNS Error" /** Resolve a request destination */ static void outgoing_resolve(nta_outgoing_t *orq, int explicit_transport, enum nta_res_order_e res_order) { struct sipdns_resolver *sr = NULL; char const *tpname = orq->orq_tpn->tpn_proto; int tport_known = strcmp(tpname, "*") != 0; if (orq->orq_agent->sa_resolver) orq->orq_resolver = sr = su_zalloc(orq->orq_agent->sa_home, (sizeof *sr)); if (!sr) { outgoing_resolving_error(orq, SIP_500_INTERNAL_SERVER_ERROR); return; } *sr->sr_tpn = *orq->orq_tpn; sr->sr_use_srv = orq->orq_agent->sa_use_srv; sr->sr_use_naptr = orq->orq_agent->sa_use_naptr && sr->sr_use_srv; sr->sr_use_a_aaaa = 1; sr->sr_tail = &sr->sr_head; /* RFC 3263: If the TARGET was not a numeric IP address, but a port is present in the URI, the client performs an A or AAAA record lookup of the domain name. The result will be a list of IP addresses, each of which can be contacted at the specific port from the URI and transport protocol determined previously. The client SHOULD try the first record. If an attempt should fail, based on the definition of failure in Section 4.3, the next SHOULD be tried, and if that should fail, the next SHOULD be tried, and so on. This is a change from RFC 2543. Previously, if the port was explicit, but with a value of 5060, SRV records were used. Now, A or AAAA records will be used. */ if (sr->sr_tpn->tpn_port) sr->sr_use_naptr = 0, sr->sr_use_srv = 0; /* RFC3263: If [...] a transport was specified explicitly, the client performs an SRV query for that specific transport, */ if (explicit_transport) sr->sr_use_naptr = 0; { /* Initialize sr_tports */ tport_t *tport; char const *ident = sr->sr_tpn->tpn_ident; int i, j; for (tport = tport_primary_by_name(orq->orq_agent->sa_tports, orq->orq_tpn); tport; tport = tport_next(tport)) { tp_name_t const *tpn = tport_name(tport); if (tport_known && !su_casematch(tpn->tpn_proto, tpname)) continue; if (ident && (tpn->tpn_ident == NULL || strcmp(ident, tpn->tpn_ident))) continue; for (j = 0; j < SIPDNS_TRANSPORTS; j++) if (su_casematch(tpn->tpn_proto, sipdns_tports[j].name)) break; assert(j < SIPDNS_TRANSPORTS); if (j == SIPDNS_TRANSPORTS) /* Someone added transport but did not update sipdns_tports */ continue; for (i = 0; i < SIPDNS_TRANSPORTS; i++) { if (sipdns_tports + j == sr->sr_tports[i] || sr->sr_tports[i] == NULL) break; } sr->sr_tports[i] = sipdns_tports + j; if (tport_known) /* Looking for only one transport */ { sr->sr_tport = sipdns_tports + j; break; } } /* Nothing found */ if (!sr->sr_tports[0]) { SU_DEBUG_3(("nta(%p): transport %s is not supported%s%s\n", (void *)orq, tpname, ident ? " by interface " : "", ident ? ident : "")); outgoing_resolving_error(orq, SIPDNS_503_ERROR); return; } } switch (res_order) { default: case nta_res_ip6_ip4: sr->sr_a_aaaa1 = sres_type_aaaa, sr->sr_a_aaaa2 = sres_type_a; break; case nta_res_ip4_ip6: sr->sr_a_aaaa1 = sres_type_a, sr->sr_a_aaaa2 = sres_type_aaaa; break; case nta_res_ip6_only: sr->sr_a_aaaa1 = sres_type_aaaa, sr->sr_a_aaaa2 = sres_type_aaaa; break; case nta_res_ip4_only: sr->sr_a_aaaa1 = sres_type_a, sr->sr_a_aaaa2 = sres_type_a; break; } outgoing_resolve_next(orq); } /** Resolve next destination. */ static int outgoing_resolve_next(nta_outgoing_t *orq) { struct sipdns_resolver *sr = orq->orq_resolver; if (orq->orq_completed) return 0; if (sr == NULL) { outgoing_resolving_error(orq, SIP_500_INTERNAL_SERVER_ERROR); return 0; } if (sr->sr_results) { /* Use existing A/AAAA results */ su_free(msg_home(orq->orq_request), sr->sr_results[0]); sr->sr_results++; if (sr->sr_results[0]) { struct sipdns_query *sq = sr->sr_current; assert(sq); if (sq->sq_proto) orq->orq_tpn->tpn_proto = sq->sq_proto; if (sq->sq_port[0]) orq->orq_tpn->tpn_port = sq->sq_port; orq->orq_tpn->tpn_host = sr->sr_results[0]; outgoing_reset_timer(orq); outgoing_queue(orq->orq_agent->sa_out.resolving, orq); outgoing_prepare_send(orq); return 1; } else { sr->sr_current = NULL; sr->sr_results = NULL; } } if (sr->sr_head) outgoing_query_all(orq); else if (sr->sr_use_naptr) outgoing_query_naptr(orq, sr->sr_tpn->tpn_host); /* NAPTR */ else if (sr->sr_use_srv) outgoing_make_srv_query(orq); /* SRV */ else if (sr->sr_use_a_aaaa) outgoing_make_a_aaaa_query(orq); /* A/AAAA */ else return outgoing_resolving_error(orq, SIPDNS_503_ERROR); return 1; } /** Check if can we retry other destinations? */ static int outgoing_other_destinations(nta_outgoing_t const *orq) { struct sipdns_resolver *sr; if (orq->orq_completed) return 0; sr = orq->orq_resolver; if (!sr) return 0; if (sr->sr_use_a_aaaa || sr->sr_use_srv || sr->sr_use_naptr) return 1; if (sr->sr_results && sr->sr_results[1]) return 1; if (sr->sr_head) return 1; return 0; } /** Resolve a request destination */ static int outgoing_try_another(nta_outgoing_t *orq) { struct sipdns_resolver *sr = orq->orq_resolver; if (sr == NULL) return 0; *orq->orq_tpn = *sr->sr_tpn; orq->orq_try_tcp_instead = 0, orq->orq_try_udp_instead = 0; outgoing_reset_timer(orq); outgoing_queue(orq->orq_agent->sa_out.resolving, orq); if (orq->orq_status > 0) /* PP: don't hack priority if a preliminary response has been received */ ; else if (orq->orq_agent->sa_graylist == 0) /* PP: priority hacking disabled */ ; /* NetModule hack: * Move server that did not work to end of queue in sres cache * * the next request does not try to use the server that is currently down * * @TODO: fix cases with only A or AAAA answering, or all servers down. */ else if (sr && sr->sr_target) { struct sipdns_query *sq; /* find latest A/AAAA record */ sq = sr->sr_head; if (sq && sq->sq_type == sr->sr_a_aaaa2 && sr->sr_a_aaaa1 != sr->sr_a_aaaa2) { sq->sq_grayish = 1; } else { outgoing_graylist(orq, sr->sr_done); } } return outgoing_resolve_next(orq); } /** Graylist SRV records */ static void outgoing_graylist(nta_outgoing_t *orq, struct sipdns_query *sq) { struct sipdns_resolver *sr = orq->orq_resolver; char const *target = sq->sq_domain, *proto = sq->sq_proto; unsigned prio = sq->sq_priority, maxprio = prio; /* Don't know how to graylist but SRV records */ if (sq->sq_otype != sres_type_srv) return; SU_DEBUG_5(("nta: graylisting %s:%s;transport=%s\n", target, sq->sq_port, proto)); for (sq = sr->sr_head; sq; sq = sq->sq_next) if (sq->sq_otype == sres_type_srv && sq->sq_priority > maxprio) maxprio = sq->sq_priority; for (sq = sr->sr_done; sq; sq = sq->sq_next) if (sq->sq_otype == sres_type_srv && sq->sq_priority > maxprio) maxprio = sq->sq_priority; for (sq = sr->sr_done; sq; sq = sq->sq_next) { int modified; if (sq->sq_type != sres_type_srv || strcmp(proto, sq->sq_proto)) continue; /* modify the SRV record(s) corresponding to the latest A/AAAA record */ modified = sres_set_cached_srv_priority( orq->orq_agent->sa_resolver, sq->sq_domain, target, sq->sq_port[0] ? (uint16_t)strtoul(sq->sq_port, NULL, 10) : 0, orq->orq_agent->sa_graylist, maxprio + 1); if (modified >= 0) SU_DEBUG_3(("nta: reduced priority of %d %s SRV records (increase value to %u)\n", modified, sq->sq_domain, maxprio + 1)); else SU_DEBUG_3(("nta: failed to reduce %s SRV priority\n", sq->sq_domain)); } } /** Cancel resolver query */ su_inline void outgoing_cancel_resolver(nta_outgoing_t *orq) { struct sipdns_resolver *sr = orq->orq_resolver; if (sr && sr->sr_query) /* Cancel resolver query */ sres_query_bind(sr->sr_query, NULL, NULL), sr->sr_query = NULL; } /** Destroy resolver */ su_inline void outgoing_destroy_resolver(nta_outgoing_t *orq) { struct sipdns_resolver *sr = orq->orq_resolver; assert(orq->orq_resolver); if (sr->sr_query) /* Cancel resolver query */ sres_query_bind(sr->sr_query, NULL, NULL), sr->sr_query = NULL; su_free(orq->orq_agent->sa_home, sr); orq->orq_resolver = NULL; } /** Check if we are resolving. If not, return 503 response. */ static int outgoing_resolving(nta_outgoing_t *orq) { struct sipdns_resolver *sr = orq->orq_resolver; assert(orq->orq_resolver); if (!sr->sr_query) { return outgoing_resolving_error(orq, SIPDNS_503_ERROR); } else { outgoing_queue(orq->orq_agent->sa_out.resolving, orq); return 0; } } /** Return 503 response */ static int outgoing_resolving_error(nta_outgoing_t *orq, int status, char const *phrase) { orq->orq_resolved = 1; outgoing_reply(orq, status, phrase, 0); return -1; } /* Query SRV records (with the given tport). */ static int outgoing_make_srv_query(nta_outgoing_t *orq) { struct sipdns_resolver *sr = orq->orq_resolver; su_home_t *home = msg_home(orq->orq_request); struct sipdns_query *sq; char const *host, *prefix; int i; size_t hlen, plen; sr->sr_use_srv = 0; host = sr->sr_tpn->tpn_host; hlen = strlen(host) + 1; for (i = 0; sr->sr_tports[i]; i++) { if (sr->sr_tport && sr->sr_tports[i] != sr->sr_tport) continue; prefix = sr->sr_tports[i]->prefix; plen = strlen(prefix); sq = su_zalloc(home, (sizeof *sq) + plen + hlen); if (sq) { *sr->sr_tail = sq, sr->sr_tail = &sq->sq_next; sq->sq_domain = memcpy(sq + 1, prefix, plen); memcpy((char *)sq->sq_domain + plen, host, hlen); sq->sq_proto = sr->sr_tports[i]->name; sq->sq_type = sres_type_srv; sq->sq_priority = 1; sq->sq_weight = 1; } } outgoing_query_all(orq); return 0; } /* Query A/AAAA records. */ static int outgoing_make_a_aaaa_query(nta_outgoing_t *orq) { struct sipdns_resolver *sr = orq->orq_resolver; su_home_t *home = msg_home(orq->orq_request); tp_name_t *tpn = orq->orq_tpn; struct sipdns_query *sq; assert(sr); sr->sr_use_a_aaaa = 0; sq = su_zalloc(home, 2 * (sizeof *sq)); if (!sq) return outgoing_resolving(orq); sq->sq_type = sr->sr_a_aaaa1; sq->sq_domain = tpn->tpn_host; sq->sq_priority = 1; /* Append */ *sr->sr_tail = sq, sr->sr_tail = &sq->sq_next; outgoing_query_all(orq); return 0; } /** Start SRV/A/AAAA queries */ static void outgoing_query_all(nta_outgoing_t *orq) { struct sipdns_resolver *sr = orq->orq_resolver; struct sipdns_query *sq = sr->sr_head; if (sq == NULL) { outgoing_resolving_error(orq, SIP_500_INTERNAL_SERVER_ERROR); return; } /* Remove from intermediate list */ if (!(sr->sr_head = sq->sq_next)) sr->sr_tail = &sr->sr_head; if (sq->sq_type == sres_type_srv) outgoing_query_srv(orq, sq); #if SU_HAVE_IN6 else if (sq->sq_type == sres_type_aaaa) outgoing_query_aaaa(orq, sq); #endif else if (sq->sq_type == sres_type_a) outgoing_query_a(orq, sq); else outgoing_resolving_error(orq, SIP_500_INTERNAL_SERVER_ERROR); } /** Query NAPTR record. */ static int outgoing_query_naptr(nta_outgoing_t *orq, char const *domain) { struct sipdns_resolver *sr = orq->orq_resolver; sres_record_t **answers; sr->sr_use_naptr = 0; sr->sr_target = domain; answers = sres_cached_answers(orq->orq_agent->sa_resolver, sres_type_naptr, domain); SU_DEBUG_5(("nta: for \"%s\" query \"%s\" %s%s\n", orq->orq_tpn->tpn_host, domain, "NAPTR", answers ? " (cached)" : "")); if (answers) { outgoing_answer_naptr(orq, NULL, answers); return 0; } else { sr->sr_query = sres_query(orq->orq_agent->sa_resolver, outgoing_answer_naptr, orq, sres_type_naptr, domain); return outgoing_resolving(orq); } } /* Process NAPTR records */ static void outgoing_answer_naptr(sres_context_t *orq, sres_query_t *q, sres_record_t *answers[]) { int i, order = -1; size_t rlen; su_home_t *home = msg_home(orq->orq_request); struct sipdns_resolver *sr = orq->orq_resolver; tp_name_t tpn[1]; struct sipdns_query *sq, *selected = NULL, **tail = &selected, **at; assert(sr); sr->sr_query = NULL; *tpn = *sr->sr_tpn; /* The NAPTR results are sorted first by Order then by Preference */ sres_sort_answers(orq->orq_agent->sa_resolver, answers); if (sr->sr_tport == NULL) sr->sr_tport = outgoing_naptr_tport(orq, answers); for (i = 0; answers && answers[i]; i++) { sres_naptr_record_t const *na = answers[i]->sr_naptr; uint16_t type; int valid_tport; if (na->na_record->r_status) continue; if (na->na_record->r_type != sres_type_naptr) continue; /* Check if NAPTR matches our target */ if (!su_casenmatch(na->na_services, "SIP+", 4) && !su_casenmatch(na->na_services, "SIPS+", 5)) /* Not a SIP/SIPS service */ continue; /* Use NAPTR results, don't try extra SRV/A/AAAA records */ sr->sr_use_srv = 0, sr->sr_use_a_aaaa = 0; valid_tport = sr->sr_tport && su_casematch(na->na_services, sr->sr_tport->service); SU_DEBUG_5(("nta: %s IN NAPTR %u %u \"%s\" \"%s\" \"%s\" %s%s\n", na->na_record->r_name, na->na_order, na->na_prefer, na->na_flags, na->na_services, na->na_regexp, na->na_replace, order >= 0 && order != na->na_order ? " (out of order)" : valid_tport ? "" : " (tport not used)")); /* RFC 2915 p 4: * Order * A 16-bit unsigned integer specifying the order in which the * NAPTR records MUST be processed to ensure the correct ordering * of rules. Low numbers are processed before high numbers, and * once a NAPTR is found whose rule "matches" the target, the * client MUST NOT consider any NAPTRs with a higher value for * order (except as noted below for the Flags field). */ if (order >= 0 && order != na->na_order) continue; if (!valid_tport) continue; /* OK, we found matching NAPTR */ order = na->na_order; /* * The "S" flag means that the next lookup should be for SRV records * ... "A" means that the next lookup should be for either an A, AAAA, * or A6 record. */ if (na->na_flags[0] == 's' || na->na_flags[0] == 'S') type = sres_type_srv; /* SRV */ else if (na->na_flags[0] == 'a' || na->na_flags[0] == 'A') type = sr->sr_a_aaaa1; /* A / AAAA */ else continue; rlen = strlen(na->na_replace) + 1; sq = su_zalloc(home, (sizeof *sq) + rlen); if (sq == NULL) continue; *tail = sq, tail = &sq->sq_next; sq->sq_otype = sres_type_naptr; sq->sq_priority = na->na_prefer; sq->sq_weight = 1; sq->sq_type = type; sq->sq_domain = memcpy(sq + 1, na->na_replace, rlen); sq->sq_proto = sr->sr_tport->name; } sres_free_answers(orq->orq_agent->sa_resolver, answers); /* RFC2915: Preference [...] specifies the order in which NAPTR records with equal "order" values SHOULD be processed, low numbers being processed before high numbers. */ at = sr->sr_tail; while (selected) { sq = selected, selected = sq->sq_next; for (tail = at; *tail; tail = &(*tail)->sq_next) { if (sq->sq_priority < (*tail)->sq_priority) break; if (sq->sq_priority == (*tail)->sq_priority && sq->sq_weight < (*tail)->sq_weight) break; } /* Insert */ sq->sq_next = *tail, *tail = sq; if (!sq->sq_next) /* Last one */ sr->sr_tail = &sq->sq_next; } outgoing_resolve_next(orq); } /* Find first supported protocol in order and preference */ struct sipdns_tport const * outgoing_naptr_tport(nta_outgoing_t *orq, sres_record_t *answers[]) { int i, j, order, pref; int orders[SIPDNS_TRANSPORTS], prefs[SIPDNS_TRANSPORTS]; struct sipdns_tport const *tport; struct sipdns_resolver *sr = orq->orq_resolver; for (j = 0; sr->sr_tports[j]; j++) { tport = sr->sr_tports[j]; orders[j] = 65536, prefs[j] = 65536; /* Find transport order */ for (i = 0; answers && answers[i]; i++) { sres_naptr_record_t const *na = answers[i]->sr_naptr; if (na->na_record->r_status) continue; if (na->na_record->r_type != sres_type_naptr) continue; /* Check if NAPTR matches transport */ if (!su_casematch(na->na_services, tport->service)) continue; orders[j] = na->na_order; prefs[j] = na->na_prefer; break; } } tport = sr->sr_tports[0], order = orders[0], pref = prefs[0]; for (j = 1; sr->sr_tports[j]; j++) { if (orders[j] <= order && prefs[j] < pref) { tport = sr->sr_tports[j], order = orders[j], pref = prefs[j]; } } return tport; } /* Query SRV records */ static int outgoing_query_srv(nta_outgoing_t *orq, struct sipdns_query *sq) { struct sipdns_resolver *sr = orq->orq_resolver; sres_record_t **answers; sr->sr_target = sq->sq_domain; sr->sr_current = sq; answers = sres_cached_answers(orq->orq_agent->sa_resolver, sres_type_srv, sq->sq_domain); SU_DEBUG_5(("nta: for \"%s\" query \"%s\" %s%s\n", orq->orq_tpn->tpn_host, sq->sq_domain, "SRV", answers ? " (cached)" : "")); if (answers) { outgoing_answer_srv(orq, NULL, answers); return 0; } else { sr->sr_query = sres_query(orq->orq_agent->sa_resolver, outgoing_answer_srv, orq, sres_type_srv, sq->sq_domain); return outgoing_resolving(orq); } } /* Process SRV records */ static void outgoing_answer_srv(sres_context_t *orq, sres_query_t *q, sres_record_t *answers[]) { struct sipdns_resolver *sr = orq->orq_resolver; su_home_t *home = msg_home(orq->orq_request); struct sipdns_query *sq0, *sq, *selected = NULL, **tail = &selected, **at; int i; size_t tlen; sr->sr_query = NULL; sq0 = sr->sr_current; assert(sq0 && sq0->sq_type == sres_type_srv); assert(sq0->sq_domain); assert(sq0->sq_proto); /* Sort by priority, weight? */ sres_sort_answers(orq->orq_agent->sa_resolver, answers); for (i = 0; answers && answers[i]; i++) { sres_srv_record_t const *srv = answers[i]->sr_srv; if (srv->srv_record->r_status /* There was an error */ || srv->srv_record->r_type != sres_type_srv) continue; tlen = strlen(srv->srv_target) + 1; sq = su_zalloc(home, (sizeof *sq) + tlen); if (sq) { *tail = sq, tail = &sq->sq_next; sq->sq_otype = sres_type_srv; sq->sq_type = sr->sr_a_aaaa1; sq->sq_proto = sq0->sq_proto; sq->sq_domain = memcpy(sq + 1, srv->srv_target, tlen); snprintf(sq->sq_port, sizeof(sq->sq_port), "%u", srv->srv_port); sq->sq_priority = srv->srv_priority; sq->sq_weight = srv->srv_weight; } } sres_free_answers(orq->orq_agent->sa_resolver, answers); at = &sr->sr_head; /* Insert sorted by priority, randomly select by weigth */ while (selected) { unsigned long weight = 0; unsigned N = 0; uint16_t priority = selected->sq_priority; /* Total weight of entries with same priority */ for (sq = selected; sq && priority == sq->sq_priority; sq = sq->sq_next) { weight += sq->sq_weight; N ++; } tail = &selected; /* Select by weighted random. Entries with weight 0 are kept in order */ if (N > 1 && weight > 0) { unsigned rand = su_randint(0, weight - 1); while (rand >= (*tail)->sq_weight) { rand -= (*tail)->sq_weight; tail = &(*tail)->sq_next; } } /* Remove selected */ sq = *tail; *tail = sq->sq_next; assert(sq->sq_priority == priority); /* Append at *at */ sq->sq_next = *at; *at = sq; at = &sq->sq_next; if (!*at) sr->sr_tail = at; SU_DEBUG_5(("nta: %s IN SRV %u %u %s %s (%s)\n", sq0->sq_domain, (unsigned)sq->sq_priority, (unsigned)sq->sq_weight, sq->sq_port, sq->sq_domain, sq->sq_proto)); } /* This is not needed anymore (?) */ sr->sr_current = NULL; sq0->sq_next = sr->sr_done; sr->sr_done = sq0; outgoing_resolve_next(orq); } #if SU_HAVE_IN6 /* Query AAAA records */ static int outgoing_query_aaaa(nta_outgoing_t *orq, struct sipdns_query *sq) { struct sipdns_resolver *sr = orq->orq_resolver; sres_record_t **answers; sr->sr_target = sq->sq_domain; sr->sr_current = sq; answers = sres_cached_answers(orq->orq_agent->sa_resolver, sres_type_aaaa, sq->sq_domain); SU_DEBUG_5(("nta: for \"%s\" query \"%s\" %s%s\n", orq->orq_tpn->tpn_host, sq->sq_domain, "AAAA", answers ? " (cached)" : "")); if (answers) { outgoing_answer_aaaa(orq, NULL, answers); return 0; } sr->sr_query = sres_query(orq->orq_agent->sa_resolver, outgoing_answer_aaaa, orq, sres_type_aaaa, sq->sq_domain); return outgoing_resolving(orq); } /* Process AAAA records */ static void outgoing_answer_aaaa(sres_context_t *orq, sres_query_t *q, sres_record_t *answers[]) { struct sipdns_resolver *sr = orq->orq_resolver; su_home_t *home = msg_home(orq->orq_request); struct sipdns_query *sq = sr->sr_current; size_t i, j, found; char *result, **results = NULL; assert(sq); assert(sq->sq_type == sres_type_aaaa); sr->sr_query = NULL; for (i = 0, found = 0; answers && answers[i]; i++) { sres_aaaa_record_t const *aaaa = answers[i]->sr_aaaa; if (aaaa->aaaa_record->r_status == 0 && aaaa->aaaa_record->r_type == sres_type_aaaa) found++; } if (found > 1) results = su_zalloc(home, (found + 1) * (sizeof *results)); else if (found) results = &result; for (i = j = 0; results && answers && answers[i]; i++) { char addr[SU_ADDRSIZE]; sres_aaaa_record_t const *aaaa = answers[i]->sr_aaaa; if (aaaa->aaaa_record->r_status || aaaa->aaaa_record->r_type != sres_type_aaaa) continue; /* There was an error */ su_inet_ntop(AF_INET6, &aaaa->aaaa_addr, addr, sizeof(addr)); if (j == 0) SU_DEBUG_5(("nta(%p): %s IN AAAA %s\n", (void *)orq, aaaa->aaaa_record->r_name, addr)); else SU_DEBUG_5(("nta(%p): AAAA %s\n", (void *)orq, addr)); assert(j < found); results[j++] = su_strdup(home, addr); } sres_free_answers(orq->orq_agent->sa_resolver, answers); outgoing_query_results(orq, sq, results, found); } #endif /* SU_HAVE_IN6 */ /* Query A records */ static int outgoing_query_a(nta_outgoing_t *orq, struct sipdns_query *sq) { struct sipdns_resolver *sr = orq->orq_resolver; sres_record_t **answers; sr->sr_target = sq->sq_domain; sr->sr_current = sq; answers = sres_cached_answers(orq->orq_agent->sa_resolver, sres_type_a, sq->sq_domain); SU_DEBUG_5(("nta: for \"%s\" query \"%s\" %s%s\n", orq->orq_tpn->tpn_host, sq->sq_domain, "A", answers ? " (cached)" : "")); if (answers) { outgoing_answer_a(orq, NULL, answers); return 0; } sr->sr_query = sres_query(orq->orq_agent->sa_resolver, outgoing_answer_a, orq, sres_type_a, sq->sq_domain); return outgoing_resolving(orq); } /* Process A records */ static void outgoing_answer_a(sres_context_t *orq, sres_query_t *q, sres_record_t *answers[]) { struct sipdns_resolver *sr = orq->orq_resolver; su_home_t *home = msg_home(orq->orq_request); struct sipdns_query *sq = sr->sr_current; int i, j, found; char *result, **results = NULL; assert(sq); assert(sq->sq_type == sres_type_a); sr->sr_query = NULL; for (i = 0, found = 0; answers && answers[i]; i++) { sres_a_record_t const *a = answers[i]->sr_a; if (a->a_record->r_status == 0 && a->a_record->r_type == sres_type_a) found++; } if (found > 1) results = su_zalloc(home, (found + 1) * (sizeof *results)); else if (found) results = &result; if (results == NULL) found = 0; for (i = j = 0; results && answers && answers[i]; i++) { char addr[SU_ADDRSIZE]; sres_a_record_t const *a = answers[i]->sr_a; if (a->a_record->r_status || a->a_record->r_type != sres_type_a) continue; /* There was an error */ su_inet_ntop(AF_INET, &a->a_addr, addr, sizeof(addr)); if (j == 0) SU_DEBUG_5(("nta: %s IN A %s\n", a->a_record->r_name, addr)); else SU_DEBUG_5(("nta(%p): A %s\n", (void *)orq, addr)); assert(j < found); results[j++] = su_strdup(home, addr); } sres_free_answers(orq->orq_agent->sa_resolver, answers); outgoing_query_results(orq, sq, results, found); } /** Store A/AAAA query results */ static void outgoing_query_results(nta_outgoing_t *orq, struct sipdns_query *sq, char *results[], size_t rlen) { struct sipdns_resolver *sr = orq->orq_resolver; if (sq->sq_type == sr->sr_a_aaaa1 && sq->sq_type != sr->sr_a_aaaa2) { sq->sq_type = sr->sr_a_aaaa2; SU_DEBUG_7(("nta(%p): %s %s record still unresolved\n", (void *)orq, sq->sq_domain, sq->sq_type == sres_type_a ? "A" : "AAAA")); /* * Three possible policies: * 1) try each host for AAAA/A, then A/AAAA * 2) try everything first for AAAA/A, then everything for A/AAAA * 3) try one SRV record results for AAAA/A, then for A/AAAA, * then next SRV record */ /* We use now policy #1 */ if (!(sq->sq_next = sr->sr_head)) sr->sr_tail = &sq->sq_next; sr->sr_head = sq; } else { sq->sq_next = sr->sr_done, sr->sr_done = sq; if (rlen == 0 && sq->sq_grayish) outgoing_graylist(orq, sq); } if (rlen > 1) sr->sr_results = results; else sr->sr_current = NULL; if (orq->orq_completed) return; if (rlen > 0) { orq->orq_resolved = 1; orq->orq_tpn->tpn_host = results[0]; if (sq->sq_proto) orq->orq_tpn->tpn_proto = sq->sq_proto; if (sq->sq_port[0]) orq->orq_tpn->tpn_port = sq->sq_port; outgoing_prepare_send(orq); } else { outgoing_resolve_next(orq); } } #endif /* ====================================================================== */ /* 10) Reliable responses */ static nta_prack_f nta_reliable_destroyed; /** * Check that server transaction can be used to send reliable provisional * responses. */ su_inline int reliable_check(nta_incoming_t *irq) { if (irq == NULL || irq->irq_status >= 200 || !irq->irq_agent) return 0; if (irq->irq_reliable && irq->irq_reliable->rel_status >= 200) return 0; /* @RSeq is initialized to nonzero when request requires/supports 100rel */ if (irq->irq_rseq == 0) return 0; if (irq->irq_rseq == 0xffffffffU) /* already sent >> 2**31 responses */ return 0; return 1; } /** Respond reliably. * * @param irq * @param callback * @param rmagic * @param status * @param phrase * @param tag, value, .. */ nta_reliable_t *nta_reliable_treply(nta_incoming_t *irq, nta_prack_f *callback, nta_reliable_magic_t *rmagic, int status, char const *phrase, tag_type_t tag, tag_value_t value, ...) { ta_list ta; msg_t *msg; sip_t *sip; nta_reliable_t *retval = NULL; if (!reliable_check(irq) || (status <= 100 || status >= 200)) return NULL; msg = nta_msg_create(irq->irq_agent, 0); sip = sip_object(msg); if (!sip) return NULL; ta_start(ta, tag, value); if (0 > nta_incoming_complete_response(irq, msg, status, phrase, ta_tags(ta))) msg_destroy(msg); else if (!(retval = reliable_mreply(irq, callback, rmagic, msg, sip))) msg_destroy(msg); ta_end(ta); return retval; } /** Respond reliably with @a msg. * * @note * The stack takes over the ownership of @a msg. (It is destroyed even if * sending the response fails.) * * @param irq * @param callback * @param rmagic * @param msg */ nta_reliable_t *nta_reliable_mreply(nta_incoming_t *irq, nta_prack_f *callback, nta_reliable_magic_t *rmagic, msg_t *msg) { sip_t *sip = sip_object(msg); if (!reliable_check(irq)) { msg_destroy(msg); return NULL; } if (sip == NULL || !sip->sip_status || sip->sip_status->st_status <= 100) { msg_destroy(msg); return NULL; } if (sip->sip_status->st_status >= 200) { incoming_final_failed(irq, msg); return NULL; } return reliable_mreply(irq, callback, rmagic, msg, sip); } static nta_reliable_t *reliable_mreply(nta_incoming_t *irq, nta_prack_f *callback, nta_reliable_magic_t *rmagic, msg_t *msg, sip_t *sip) { nta_reliable_t *rel; nta_agent_t *agent; agent = irq->irq_agent; if (callback == NULL) callback = nta_reliable_destroyed; rel = su_zalloc(agent->sa_home, sizeof(*rel)); if (rel) { rel->rel_irq = irq; rel->rel_callback = callback; rel->rel_magic = rmagic; rel->rel_unsent = msg; rel->rel_status = sip->sip_status->st_status; rel->rel_precious = sip->sip_payload != NULL; rel->rel_next = irq->irq_reliable; /* * If there already is a un-pr-acknowledged response, queue this one * until at least one response is pr-acknowledged. */ if (irq->irq_reliable && (irq->irq_reliable->rel_next == NULL || irq->irq_reliable->rel_rseq == 0)) { return irq->irq_reliable = rel; } if (reliable_send(irq, rel, msg_ref(msg), sip) < 0) { msg_destroy(msg); su_free(agent->sa_home, rel); return NULL; } irq->irq_reliable = rel; return callback ? rel : (nta_reliable_t *)-1; } msg_destroy(msg); return NULL; } static int reliable_send(nta_incoming_t *irq, nta_reliable_t *rel, msg_t *msg, sip_t *sip) { nta_agent_t *sa = irq->irq_agent; su_home_t *home = msg_home(msg); sip_rseq_t rseq[1]; sip_rseq_init(rseq); if (sip->sip_require) msg_header_replace_param(home, sip->sip_require->k_common, "100rel"); else sip_add_make(msg, sip, sip_require_class, "100rel"); rel->rel_rseq = rseq->rs_response = irq->irq_rseq; sip_add_dup(msg, sip, (sip_header_t *)rseq); if (!sip->sip_rseq || incoming_reply(irq, msg, sip) < 0) { msg_destroy(msg); return -1; } irq->irq_rseq++; if (irq->irq_queue == sa->sa_in.preliminary) /* Make sure we are moved to the tail */ incoming_remove(irq); incoming_queue(sa->sa_in.preliminary, irq); /* P1 */ incoming_set_timer(irq, sa->sa_t1); /* P2 */ return 0; } /** Queue final response when there are unsent precious preliminary responses */ static int reliable_final(nta_incoming_t *irq, msg_t *msg, sip_t *sip) { nta_reliable_t *r; unsigned already_in_callback; /* * We delay sending final response if it's 2XX and * an unpracked reliable response contains session description */ /* Get last unpracked response from queue */ if (sip->sip_status->st_status < 300) for (r = irq->irq_reliable; r; r = r->rel_next) if (r->rel_unsent && r->rel_precious) { /* Delay sending 2XX */ reliable_mreply(irq, NULL, NULL, msg, sip); return 0; } /* Flush unsent responses. */ already_in_callback = irq->irq_in_callback; irq->irq_in_callback = 1; reliable_flush(irq); irq->irq_in_callback = already_in_callback; if (!already_in_callback && irq->irq_terminated && irq->irq_destroyed) { incoming_free(irq); msg_destroy(msg); return 0; } return 1; } /** Get latest reliably sent response */ static msg_t *reliable_response(nta_incoming_t *irq) { nta_reliable_t *r, *rel; /* Get last unpracked response from queue */ for (rel = NULL, r = irq->irq_reliable; r; r = r->rel_next) if (!r->rel_pracked) rel = r; assert(rel); return rel->rel_unsent; } /* Find un-PRACKed responses */ static nta_reliable_t *reliable_find(nta_agent_t const *agent, sip_t const *sip) { incoming_htable_t const *iht = agent->sa_incoming; nta_incoming_t *irq, **ii; sip_call_id_t const *i = sip->sip_call_id; sip_rack_t const *rack = sip->sip_rack; hash_value_t hash = NTA_HASH(i, rack->ra_cseq); /* XXX - add own hash table for 100rel */ for (ii = incoming_htable_hash(iht, hash); (irq = *ii); ii = incoming_htable_next(iht, ii)) { if (hash == irq->irq_hash && irq->irq_call_id->i_hash == i->i_hash && irq->irq_cseq->cs_seq == rack->ra_cseq && irq->irq_method == sip_method_invite && strcmp(irq->irq_call_id->i_id, i->i_id) == 0 && (irq->irq_to->a_tag == NULL || su_casematch(irq->irq_to->a_tag, sip->sip_to->a_tag)) && su_casematch(irq->irq_from->a_tag, sip->sip_from->a_tag)) { nta_reliable_t const *rel; /* Found matching INVITE */ for (rel = irq->irq_reliable; rel; rel = rel->rel_next) if (rel->rel_rseq == rack->ra_response) return (nta_reliable_t *)rel; return NULL; } } return NULL; } /** Process incoming PRACK with matching @RAck field */ static int reliable_recv(nta_reliable_t *rel, msg_t *msg, sip_t *sip, tport_t *tp) { nta_incoming_t *irq = rel->rel_irq; nta_incoming_t *pr_irq; int status; rel->rel_pracked = 1; msg_unref(rel->rel_unsent), rel->rel_unsent = NULL; pr_irq = incoming_create(irq->irq_agent, msg, sip, tp, irq->irq_tag); if (!pr_irq) { mreply(irq->irq_agent, NULL, SIP_500_INTERNAL_SERVER_ERROR, msg, tp, 0, 0, NULL, TAG_END()); return 0; } if (irq->irq_status < 200) { incoming_queue(irq->irq_agent->sa_in.proceeding, irq); /* Reset P1 */ incoming_reset_timer(irq); /* Reset P2 */ } irq->irq_in_callback = pr_irq->irq_in_callback = 1; status = rel->rel_callback(rel->rel_magic, rel, pr_irq, sip); rel = NULL; irq->irq_in_callback = pr_irq->irq_in_callback = 0; if (pr_irq->irq_completed) { /* Already sent final response */ if (pr_irq->irq_terminated && pr_irq->irq_destroyed) incoming_free(pr_irq); } else if (status != 0) { if (status < 200 || status > 299) { SU_DEBUG_3(("nta_reliable(): invalid status %03d from callback\n", status)); status = 200; } nta_incoming_treply(pr_irq, status, "OK", TAG_END()); nta_incoming_destroy(pr_irq); } /* If there are queued unsent reliable responses, send them all. */ while (irq->irq_reliable && irq->irq_reliable->rel_rseq == 0) { nta_reliable_t *r; for (r = irq->irq_reliable; r; r = r->rel_next) if (r->rel_rseq == 0) rel = r; msg = rel->rel_unsent, sip = sip_object(msg); if (sip->sip_status->st_status < 200) { if (reliable_send(irq, rel, msg_ref(msg), sip) < 0) { assert(!"send reliable response"); } } else { /* * XXX * Final response should be delayed until a reliable provisional * response has been pracked */ rel->rel_unsent = NULL, rel->rel_rseq = (uint32_t)-1; if (incoming_reply(irq, msg, sip) < 0) { assert(!"send delayed final response"); } } } return 0; } /** Flush unacknowledged and unsent reliable responses */ void reliable_flush(nta_incoming_t *irq) { nta_reliable_t *r, *rel; do { for (r = irq->irq_reliable, rel = NULL; r; r = r->rel_next) if (r->rel_unsent) rel = r; if (rel) { rel->rel_pracked = 1; msg_unref(rel->rel_unsent), rel->rel_unsent = NULL; rel->rel_callback(rel->rel_magic, rel, NULL, NULL); } } while (rel); } void reliable_timeout(nta_incoming_t *irq, int timeout) { if (timeout) SU_DEBUG_5(("nta: response timeout with %u\n", irq->irq_status)); irq->irq_in_callback = 1; reliable_flush(irq); if (irq->irq_callback) irq->irq_callback(irq->irq_magic, irq, NULL); irq->irq_in_callback = 0; if (!timeout) return; if (irq->irq_completed && irq->irq_destroyed) incoming_free(irq), irq = NULL; else if (irq->irq_status < 200) nta_incoming_treply(irq, 503, "Reliable Response Time-Out", TAG_END()); } #if 0 /* Not needed, yet. */ /** Use this callback when normal leg callback is supposed to * process incoming PRACK requests */ int nta_reliable_leg_prack(nta_reliable_magic_t *magic, nta_reliable_t *rel, nta_incoming_t *irq, sip_t const *sip) { nta_agent_t *agent; nta_leg_t *leg; char const *method_name; url_t url[1]; int retval; if (irq == NULL || sip == NULL || rel == NULL || sip_object(irq->irq_request) != sip) return 500; agent = irq->irq_agent; method_name = sip->sip_request->rq_method_name; *url = *sip->sip_request->rq_url; url->url_params = NULL; agent_aliases(agent, url, irq->irq_tport); /* canonize urls */ if ((leg = leg_find(irq->irq_agent, method_name, url, sip->sip_call_id, sip->sip_from->a_tag, sip->sip_to->a_tag))) { /* Use existing dialog */ SU_DEBUG_5(("nta: %s (%u) %s\n", method_name, sip->sip_cseq->cs_seq, "PRACK processed by default callback, too")); retval = leg->leg_callback(leg->leg_magic, leg, irq, sip); } else { retval = 500; } nta_reliable_destroy(rel); return retval; } #endif /** Destroy a reliable response. * * Mark a reliable response object for destroyal and free it if possible. */ void nta_reliable_destroy(nta_reliable_t *rel) { if (rel == NULL || rel == NONE) return; if (rel->rel_callback == nta_reliable_destroyed) SU_DEBUG_1(("%s(%p): %s\n", __func__, (void *)rel, "already destroyed")); rel->rel_callback = nta_reliable_destroyed; if (rel->rel_response) return; nta_reliable_destroyed(NULL, rel, NULL, NULL); } /** Free and unallocate the nta_reliable_t structure. */ static int nta_reliable_destroyed(nta_reliable_magic_t *rmagic, nta_reliable_t *rel, nta_incoming_t *prack, sip_t const *sip) { nta_reliable_t **prev; assert(rel); assert(rel->rel_irq); for (prev = &rel->rel_irq->irq_reliable; *prev; prev = &(*prev)->rel_next) if (*prev == rel) break; if (!*prev) { assert(*prev); SU_DEBUG_1(("%s(%p): %s\n", __func__, (void *)rel, "not linked")); return 200; } *prev = rel->rel_next; if (rel->rel_unsent) msg_destroy(rel->rel_unsent), rel->rel_unsent = NULL; su_free(rel->rel_irq->irq_agent->sa_home, rel); return 200; } /** Validate a reliable response. */ int outgoing_recv_reliable(nta_outgoing_t *orq, msg_t *msg, sip_t *sip) { short status = sip->sip_status->st_status; char const *phrase = sip->sip_status->st_phrase; uint32_t rseq = sip->sip_rseq->rs_response; SU_DEBUG_7(("nta: %03u %s is reliably received with RSeq: %u\n", status, phrase, rseq)); /* Cannot handle reliable responses unless we have a full dialog */ if (orq->orq_rseq == 0 && !orq->orq_to->a_tag) { SU_DEBUG_5(("nta: %03u %s with initial RSeq: %u outside dialog\n", status, phrase, rseq)); return 0; } if (rseq <= orq->orq_rseq) { SU_DEBUG_3(("nta: %03u %s already received (RSeq: %u, expecting %u)\n", status, phrase, rseq, orq->orq_rseq + 1)); return -1; } if (orq->orq_rseq && orq->orq_rseq + 1 != rseq) { SU_DEBUG_3(("nta: %03d %s is not expected (RSeq: %u, expecting %u)\n", status, sip->sip_status->st_phrase, rseq, orq->orq_rseq + 1)); return -1; } return 0; } /** Create a tagged fork of outgoing request. * * When a dialog-creating INVITE request is forked, each response from * diffent fork will create an early dialog with a distinct tag in @To * header. When each fork should be handled separately, a tagged INVITE * request can be used. It will only receive responses from the specified * fork. * * Please note that the tagged INVITE transaction is terminated with the * final response from another fork, too. Stack will generate a 408 * response to all tagged INVITE transactions when the original INVITE * transaction is terminated. * * @param orq * @param callback * @param magic * @param to_tag * @param rseq * * @bug Fix the memory leak - either one of the requests is left unreleased * for ever. */ nta_outgoing_t *nta_outgoing_tagged(nta_outgoing_t *orq, nta_response_f *callback, nta_outgoing_magic_t *magic, char const *to_tag, sip_rseq_t const *rseq) { nta_agent_t *agent; su_home_t *home; nta_outgoing_t *tagged; sip_to_t *to; if (orq == NULL || to_tag == NULL) return NULL; if (orq->orq_to->a_tag) { SU_DEBUG_1(("%s: transaction %p (CSeq: %s %u) already in dialog\n", __func__, (void *)orq, orq->orq_cseq->cs_method_name, orq->orq_cseq->cs_seq)); return NULL; } if (orq->orq_method != sip_method_invite) { SU_DEBUG_1(("%s: transaction %p (CSeq: %s %u) cannot be tagged\n", __func__, (void *)orq, orq->orq_cseq->cs_method_name, orq->orq_cseq->cs_seq)); return NULL; } if (orq->orq_status < 100) { SU_DEBUG_1(("%s: transaction %p (CSeq: %s %u) still calling\n", __func__, (void *)orq, orq->orq_cseq->cs_method_name, orq->orq_cseq->cs_seq)); return NULL; } assert(orq->orq_agent); assert(orq->orq_request); agent = orq->orq_agent; tagged = su_zalloc(agent->sa_home, sizeof(*tagged)); if (!tagged) return NULL; home = msg_home((msg_t *)orq->orq_request); tagged->orq_hash = orq->orq_hash; tagged->orq_agent = orq->orq_agent; tagged->orq_callback = callback; tagged->orq_magic = magic; tagged->orq_method = orq->orq_method; tagged->orq_method_name = orq->orq_method_name; tagged->orq_url = orq->orq_url; tagged->orq_from = orq->orq_from; sip_to_tag(home, to = sip_to_copy(home, orq->orq_to), to_tag); tagged->orq_to = to; tagged->orq_tag = to->a_tag; tagged->orq_cseq = orq->orq_cseq; tagged->orq_call_id = orq->orq_call_id; tagged->orq_request = msg_ref(orq->orq_request); tagged->orq_response = msg_ref(orq->orq_response); tagged->orq_status = orq->orq_status; tagged->orq_via_added = orq->orq_via_added; tagged->orq_prepared = orq->orq_prepared; tagged->orq_reliable = orq->orq_reliable; tagged->orq_sips = orq->orq_sips; tagged->orq_uas = orq->orq_uas; tagged->orq_pass_100 = orq->orq_pass_100; tagged->orq_must_100rel = orq->orq_must_100rel; tagged->orq_100rel = orq->orq_100rel; tagged->orq_route = orq->orq_route; *tagged->orq_tpn = *orq->orq_tpn; tagged->orq_tport = tport_ref(orq->orq_tport); if (orq->orq_cc) tagged->orq_cc = nta_compartment_ref(orq->orq_cc); tagged->orq_branch = orq->orq_branch; tagged->orq_via_branch = orq->orq_via_branch; if (tagged->orq_uas) { tagged->orq_forking = orq; tagged->orq_forks = orq->orq_forks; tagged->orq_forked = 1; orq->orq_forks = tagged; } outgoing_insert(agent, tagged); return tagged; } /**PRACK a provisional response. * * Create and send a PRACK request used to acknowledge a provisional * response. * * The request is sent using the route of the original request @a oorq. * * When NTA receives response to the prack request, it invokes the @a * callback function. * * @param leg dialog object * @param oorq original transaction request * @param callback callback function (may be @c NULL) * @param magic application context pointer * @param route_url optional URL used to route transaction requests * @param resp (optional) response message to be acknowledged * @param tag,value,... optional * * @return * If successful, return a pointer to newly created client transaction * object for PRACK request, NULL otherwise. * * @sa * nta_outgoing_tcreate(), nta_outgoing_tcancel(), nta_outgoing_destroy(). */ nta_outgoing_t *nta_outgoing_prack(nta_leg_t *leg, nta_outgoing_t *oorq, nta_response_f *callback, nta_outgoing_magic_t *magic, url_string_t const *route_url, sip_t const *resp, tag_type_t tag, tag_value_t value, ...) { ta_list ta; msg_t *msg; su_home_t *home; sip_t *sip; sip_to_t const *to = NULL; sip_route_t *route = NULL, r0[1]; nta_outgoing_t *orq = NULL; sip_rack_t *rack = NULL, rack0[1]; if (!leg || !oorq) { SU_DEBUG_1(("%s: invalid arguments\n", __func__)); return NULL; } sip_rack_init(rack0); if (resp) { if (!resp->sip_status) { SU_DEBUG_1(("%s: invalid arguments\n", __func__)); return NULL; } if (resp->sip_status->st_status <= 100 || resp->sip_status->st_status >= 200) { SU_DEBUG_1(("%s: %u response cannot be PRACKed\n", __func__, resp->sip_status->st_status)); return NULL; } if (!resp->sip_rseq) { SU_DEBUG_1(("%s: %u response missing RSeq\n", __func__, resp->sip_status->st_status)); return NULL; } if (resp->sip_rseq->rs_response <= oorq->orq_rseq) { SU_DEBUG_1(("%s: %u response RSeq does not match received RSeq\n", __func__, resp->sip_status->st_status)); return NULL; } if (!oorq->orq_must_100rel && !sip_has_feature(resp->sip_require, "100rel")) { SU_DEBUG_1(("%s: %u response does not require 100rel\n", __func__, resp->sip_status->st_status)); return NULL; } if (!resp->sip_to->a_tag) { SU_DEBUG_1(("%s: %u response has no To tag\n", __func__, resp->sip_status->st_status)); return NULL; } if (su_strcasecmp(resp->sip_to->a_tag, leg->leg_remote->a_tag) || su_strcasecmp(resp->sip_to->a_tag, oorq->orq_to->a_tag)) { SU_DEBUG_1(("%s: %u response To tag does not agree with dialog tag\n", __func__, resp->sip_status->st_status)); return NULL; } to = resp->sip_to; rack = rack0; rack->ra_response = resp->sip_rseq->rs_response; rack->ra_cseq = resp->sip_cseq->cs_seq; rack->ra_method = resp->sip_cseq->cs_method; rack->ra_method_name = resp->sip_cseq->cs_method_name; } msg = nta_msg_create(leg->leg_agent, 0); sip = sip_object(msg); home = msg_home(msg); if (!sip) return NULL; if (!leg->leg_route && resp) { /* Insert contact into route */ if (resp->sip_contact) { sip_route_init(r0)->r_url[0] = resp->sip_contact->m_url[0]; route = sip_route_dup(home, r0); } /* Reverse record route */ if (resp->sip_record_route) { sip_route_t *r, *r_next; for (r = sip_route_dup(home, resp->sip_record_route); r; r = r_next) { r_next = r->r_next, r->r_next = route, route = r; } } } ta_start(ta, tag, value); if (!resp) { tagi_t const *t; if ((t = tl_find(ta_args(ta), ntatag_rseq)) && t->t_value) { rack = rack0; rack->ra_response = (uint32_t)t->t_value; } if (rack) { rack->ra_cseq = oorq->orq_cseq->cs_seq; rack->ra_method = oorq->orq_cseq->cs_method; rack->ra_method_name = oorq->orq_cseq->cs_method_name; } } if (sip_add_tl(msg, sip, TAG_IF(rack, SIPTAG_RACK(rack)), TAG_IF(to, SIPTAG_TO(to)), ta_tags(ta)) < 0) ; else if (route && sip_add_dup(msg, sip, (sip_header_t *)route) < 0) ; else if (!sip->sip_rack) SU_DEBUG_1(("%s: RAck header missing\n", __func__)); else if (nta_msg_request_complete(msg, leg, SIP_METHOD_PRACK, (url_string_t *)oorq->orq_url) < 0) ; else orq = outgoing_create(leg->leg_agent, callback, magic, route_url, NULL, msg, ta_tags(ta)); ta_end(ta); if (!orq) msg_destroy(msg); else if (rack) oorq->orq_rseq = rack->ra_response; else if (sip->sip_rack) oorq->orq_rseq = sip->sip_rack->ra_response; return orq; } /** Get @RSeq value stored with client transaction. */ uint32_t nta_outgoing_rseq(nta_outgoing_t const *orq) { return orq ? orq->orq_rseq : 0; } /** Set @RSeq value stored with client transaction. * * @return 0 if rseq was set successfully * @return -1 if rseq is invalid or orq is NULL. */ int nta_outgoing_setrseq(nta_outgoing_t *orq, uint32_t rseq) { if (orq && orq->orq_rseq <= rseq) { orq->orq_rseq = rseq; return 0; } return -1; } /* ------------------------------------------------------------------------ */ /* 11) SigComp handling and public transport interface */ #include <sofia-sip/nta_tport.h> /** Return the master transport for the agent. * * @NEW_1_12_11 */ tport_t * nta_agent_tports(nta_agent_t *agent) { return agent ? agent->sa_tports : NULL; } su_inline tport_t * nta_transport_(nta_agent_t *agent, nta_incoming_t *irq, msg_t *msg) { if (irq) return irq->irq_tport; else if (agent && msg) return tport_delivered_by(agent->sa_tports, msg); errno = EINVAL; return NULL; } /** Return a new reference to the transaction transport. * * @note The referenced transport must be unreferenced with tport_unref() */ tport_t * nta_incoming_transport(nta_agent_t *agent, nta_incoming_t *irq, msg_t *msg) { return tport_ref(nta_transport_(agent, irq, msg)); } nta_compressor_t *nta_agent_init_sigcomp(nta_agent_t *sa) { if (!nta_compressor_vtable || !sa) return NULL; if (sa->sa_compressor == NULL) { char const * const *l = sa->sa_sigcomp_option_list; nta_compressor_t *comp; comp = nta_compressor_vtable->ncv_init_agent(sa, l); sa->sa_compressor = comp; } return sa->sa_compressor; } void nta_agent_deinit_sigcomp(nta_agent_t *sa) { if (nta_compressor_vtable && sa && sa->sa_compressor) { nta_compressor_vtable->ncv_deinit_agent(sa, sa->sa_compressor); sa->sa_compressor = NULL; } } struct sigcomp_compartment * nta_incoming_compartment(nta_incoming_t *irq) { if (nta_compressor_vtable && irq && irq->irq_cc) return nta_compressor_vtable->ncv_compartment_ref(irq->irq_cc); else return NULL; } tport_t * nta_outgoing_transport(nta_outgoing_t *orq) { if (orq) return tport_ref(orq->orq_tport); else return NULL; } struct sigcomp_compartment * nta_outgoing_compartment(nta_outgoing_t *orq) { if (nta_compressor_vtable && orq && orq->orq_cc) return nta_compressor_vtable->ncv_compartment_ref(orq->orq_cc); else return NULL; } struct sigcomp_compartment * nta_compartment_ref(struct sigcomp_compartment *cc) { if (nta_compressor_vtable) return nta_compressor_vtable->ncv_compartment_ref(cc); else return NULL; } void nta_compartment_decref(struct sigcomp_compartment **pcc) { if (nta_compressor_vtable && pcc && *pcc) nta_compressor_vtable->ncv_compartment_unref(*pcc), *pcc = NULL; } /** Get compartment for connection, create it when needed. */ static struct sigcomp_compartment * agent_compression_compartment(nta_agent_t *sa, tport_t *tp, tp_name_t const *tpn, int new_if_needed) { if (nta_compressor_vtable) { char const * const *l = sa->sa_sigcomp_option_list; return nta_compressor_vtable-> ncv_compartment(sa, tp, sa->sa_compressor, tpn, l, new_if_needed); } else return NULL; } static int agent_accept_compressed(nta_agent_t *sa, msg_t *msg, struct sigcomp_compartment *cc) { if (nta_compressor_vtable) { nta_compressor_t *msc = sa->sa_compressor; tport_compressor_t *sc = NULL; if (tport_delivered_with_comp(sa->sa_tports, msg, &sc) < 0) return 0; return nta_compressor_vtable->ncv_accept_compressed(sa, msc, sc, msg, cc); } else return 0; } /** Close compressor (lose its state). */ static int agent_close_compressor(nta_agent_t *sa, struct sigcomp_compartment *cc) { if (nta_compressor_vtable) return nta_compressor_vtable->ncv_close_compressor(sa, cc); return 0; } /** Close both compressor and decompressor */ static int agent_zap_compressor(nta_agent_t *sa, struct sigcomp_compartment *cc) { if (nta_compressor_vtable) return nta_compressor_vtable->ncv_zap_compressor(sa, cc); return 0; } /** Bind transport update callback */ int nta_agent_bind_tport_update(nta_agent_t *agent, nta_update_magic_t *magic, nta_update_tport_f *callback) { if (!agent) return su_seterrno(EFAULT); agent->sa_update_magic = magic; agent->sa_update_tport = callback; return 0; } /** Check if public transport binding is in progress */ int nta_agent_tport_is_updating(nta_agent_t *agent) { return agent && tport_is_updating(agent->sa_tports); } /** Initiate STUN keepalive controller to TPORT */ int nta_tport_keepalive(nta_outgoing_t *orq) { assert(orq); #if HAVE_SOFIA_STUN return tport_keepalive(orq->orq_tport, msg_addrinfo(orq->orq_request), TAG_END()); #else return -1; #endif } /** Close all transports. @since Experimental in @VERSION_1_12_2. */ int nta_agent_close_tports(nta_agent_t *agent) { size_t i; outgoing_htable_t *oht = agent->sa_outgoing; incoming_htable_t *iht = agent->sa_incoming; for (i = oht->oht_size; i-- > 0;) /* while */ if (oht->oht_table[i]) { nta_outgoing_t *orq = oht->oht_table[i]; if (orq->orq_pending && orq->orq_tport) tport_release(orq->orq_tport, orq->orq_pending, orq->orq_request, NULL, orq, 0); orq->orq_pending = 0; tport_unref(orq->orq_tport), orq->orq_tport = NULL; } for (i = iht->iht_size; i-- > 0;) /* while */ if (iht->iht_table[i]) { nta_incoming_t *irq = iht->iht_table[i]; tport_unref(irq->irq_tport), irq->irq_tport = NULL; } tport_destroy(agent->sa_tports), agent->sa_tports = NULL; msg_header_free(agent->sa_home, (void *)agent->sa_vias); agent->sa_vias = NULL; msg_header_free(agent->sa_home, (void *)agent->sa_public_vias); agent->sa_public_vias = NULL; return 0; }
RestComm/Restcomm-Mayday
ios/MayDay/dependencies/sources/sofia-sip/libsofia-sip-ua/nta/nta.c
C
agpl-3.0
328,976
/* This file is part of VoltDB. * Copyright (C) 2008-2017 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.Serializable; import org.voltcore.logging.VoltLogger; import org.voltcore.utils.CoreUtils; import org.voltdb.processtools.ShellTools; public class PlatformProperties implements Serializable { private static final VoltLogger hostLog = new VoltLogger("HOST"); ///////////////////////////////// // ACTUAL PLATFORM PROPERTIES ///////////////////////////////// // hardware public final int ramInMegabytes; public final int hardwareThreads; public final int coreCount; public final int socketCount; public final String cpuDesc; public final boolean isCoreReportedByJava; // operating system public final String osArch; public final String osVersion; public final String osName; public final String locale; // java public final String javaVersion; public final String javaRuntime; public final String javaVMInfo; ///////////////////////////////// // CONSTRUCTOR TO SET PROPERTIES ///////////////////////////////// protected static class HardwareInfo { int ramInMegabytes = -1; int hardwareThreads = -1; int coreCount = -1; int socketCount = -1; String cpuDesc = "unknown"; } protected HardwareInfo getMacHardwareInfo() { HardwareInfo hw = new HardwareInfo(); hw.hardwareThreads = CoreUtils.availableProcessors(); String result = ShellTools.local_cmd("/usr/sbin/system_profiler -detailLevel mini SPHardwareDataType").trim(); String[] lines = result.split("\n"); for (String line : lines) { line = line.trim(); if (line.length() == 0) continue; String[] parts = line.split(":"); if (parts.length < 2) continue; if (parts[0].compareToIgnoreCase("Processor Name") == 0) { hw.cpuDesc = parts[1].trim(); } if (parts[0].compareToIgnoreCase("Processor Speed") == 0) { hw.cpuDesc += " " + parts[1].trim(); } if (parts[0].compareToIgnoreCase("Number of Processors") == 0) { hw.socketCount = Integer.valueOf(parts[1].trim()); } if (parts[0].compareToIgnoreCase("Total Number of Cores") == 0) { hw.coreCount = Integer.valueOf(parts[1].trim()); } if (parts[0].compareToIgnoreCase("L2 Cache (per Core)") == 0) { hw.cpuDesc += " " + parts[1].trim() + " L2/core"; } if (parts[0].compareToIgnoreCase("L3 Cache") == 0) { hw.cpuDesc += " " + parts[1].trim() + " L3"; } if (parts[0].compareToIgnoreCase("Memory") == 0) { String[] subParts = parts[1].trim().split(" "); if (subParts[1].contains("GB")) { hw.ramInMegabytes = Integer.parseInt(subParts[0]) * 1024; } else { assert(subParts[1].contains("MB")); hw.ramInMegabytes = Integer.parseInt(subParts[0]); } } } return hw; } protected HardwareInfo getLinuxHardwareInfo() { HardwareInfo hw = new HardwareInfo(); // determine ram try { File statFile = new File("/proc/meminfo"); FileInputStream fis = new FileInputStream(statFile); try { BufferedReader r = new BufferedReader(new InputStreamReader(fis)); String stats = r.readLine(); String[] parts = stats.split("\\s+"); long memInKB = Long.parseLong(parts[1]); hw.ramInMegabytes = (int) (memInKB / 1024); } finally { fis.close(); } } catch (Exception e) { hostLog.fatal("Unable to read /proc/meminfo. Exiting."); System.exit(-1); } // determine cpuinfo StringBuilder sb = new StringBuilder(); try { File statFile = new File("/proc/cpuinfo"); FileInputStream fis = new FileInputStream(statFile); try { BufferedReader r = new BufferedReader(new InputStreamReader(fis)); String line = null; while ((line = r.readLine()) != null) sb.append(line).append("\n"); } finally { fis.close(); } } catch (Exception e) { hostLog.fatal("Unable to read /proc/cpuinfo. Exiting."); System.exit(-1); } String[] cpus = sb.toString().trim().split("\n\n"); hw.hardwareThreads = cpus.length; // almost everything we need is in the first cpu's info section String[] lines = cpus[0].trim().split("\n"); for (String line : lines) { String[] parts = line.trim().split(":"); if (parts.length < 2) continue; if (parts[0].trim().compareToIgnoreCase("model name") == 0) { hw.cpuDesc = parts[1].trim(); } if (parts[0].trim().compareToIgnoreCase("cache size") == 0) { hw.cpuDesc += " " + parts[1].trim() + " cache"; } if (parts[0].trim().compareToIgnoreCase("siblings") == 0) { hw.socketCount = hw.hardwareThreads / Integer.parseInt(parts[1].trim()); } if (parts[0].trim().compareToIgnoreCase("cpu cores") == 0) { hw.coreCount = Integer.parseInt(parts[1].trim()) * hw.socketCount; } } return hw; } protected PlatformProperties() { HardwareInfo hw = null; if (System.getProperty("os.name").toLowerCase().contains("mac")) { hw = getMacHardwareInfo(); } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { hw = getLinuxHardwareInfo(); } else { hostLog.warn("Unable to determine supported operating system. Hardware info such as Memory,CPU will be incorrectly reported."); hw = new HardwareInfo(); } // hardware ramInMegabytes = hw.ramInMegabytes; hardwareThreads = hw.hardwareThreads; if (hw.coreCount == -1) { // some VMs don't provide cpu core count coreCount = Runtime.getRuntime().availableProcessors(); isCoreReportedByJava = true; } else { coreCount = hw.coreCount; isCoreReportedByJava = false; } socketCount = hw.socketCount; cpuDesc = hw.cpuDesc; // operating system osArch = System.getProperty("os.arch"); osVersion = System.getProperty("os.version"); osName = System.getProperty("os.name"); locale = System.getProperty("user.language") + "_" + System.getProperty("user.country"); // java javaVersion = System.getProperty("java.version"); javaRuntime = String.format("%s (%s)", System.getProperty("java.runtime.name"), System.getProperty("java.runtime.version")); javaVMInfo = String.format("%s (%s, %s)", System.getProperty("java.vm.name"), System.getProperty("java.vm.version"), System.getProperty("java.vm.info")); } ///////////////////////////////// // OUTPUT AND FORMATTING ///////////////////////////////// public String toLogLines(String dbVersion) { StringBuilder sb = new StringBuilder(); sb.append(String.format("CPU INFO: %d Cores%s, %d Sockets, %d Hardware Threads\n", coreCount, isCoreReportedByJava ? " (Reported by Java)" : "", socketCount, hardwareThreads)); sb.append(String.format("CPU DESC: %s\n", cpuDesc)); sb.append(String.format("HOST MEMORY (MB): %d\n", ramInMegabytes)); sb.append(String.format("OS PROFILE: %s %s %s %s\n", osName, osVersion, osArch, locale)); sb.append(String.format("DB VERSION: %s\n", dbVersion)); sb.append(String.format("JAVA VERSION: %s\n", javaVersion)); sb.append(String.format("JAVA RUNTIME: %s\n", javaRuntime)); sb.append(String.format("JAVA VM: %s\n", javaVMInfo)); return sb.toString(); } public String toHTML() { StringBuilder sb = new StringBuilder(); sb.append("<tt>"); sb.append(String.format("CPU INFO: %d Cores%s, %d Sockets, %d Hardware Threads<br/>\n", coreCount, isCoreReportedByJava ? " (Reported by Java)" : "", socketCount, hardwareThreads)); sb.append(String.format("CPU DESC: %s<br/>\n", cpuDesc)); sb.append(String.format("HOST MEMORY (MB): %d<br/>\n", ramInMegabytes)); sb.append(String.format("OS PROFILE: %s %s %s %s<br/>\n", osName, osVersion, osArch, locale)); sb.append(String.format("JAVA VERSION: %s<br/>\n", javaVersion)); sb.append(String.format("JAVA RUNTIME: %s<br/>\n", javaRuntime)); sb.append(String.format("JAVA VM: %s<br/>\n", javaVMInfo)); sb.append("</tt>"); return sb.toString(); } ///////////////////////////////// // STATIC CODE ///////////////////////////////// protected static PlatformProperties m_singletonProperties = null; private static final long serialVersionUID = 1841311119700809716L; public synchronized static PlatformProperties getPlatformProperties() { if (m_singletonProperties != null) return m_singletonProperties; m_singletonProperties = new PlatformProperties(); assert(m_singletonProperties != null); return m_singletonProperties; } /** * @param args */ public static void main(String[] args) { PlatformProperties pp = getPlatformProperties(); System.out.println(pp.toLogLines("")); } }
migue/voltdb
src/frontend/org/voltdb/utils/PlatformProperties.java
Java
agpl-3.0
11,026
#!/bin/bash { # this ensures the entire script is downloaded # nvm_has() { type "$1" > /dev/null 2>&1 } if [ -z "$NVM_DIR" ]; then NVM_DIR="$HOME/.nvm" fi nvm_latest_version() { echo "v0.30.1" } # # Outputs the location to NVM depending on: # * The availability of $NVM_SOURCE # * The method used ("script" or "git" in the script, defaults to "git") # NVM_SOURCE always takes precedence unless the method is "script-nvm-exec" # nvm_source() { local NVM_METHOD NVM_METHOD="$1" local NVM_SOURCE_URL NVM_SOURCE_URL="$NVM_SOURCE" if [ "_$NVM_METHOD" = "_script-nvm-exec" ]; then NVM_SOURCE_URL="https://raw.githubusercontent.com/creationix/nvm/$(nvm_latest_version)/nvm-exec" elif [ -z "$NVM_SOURCE_URL" ]; then if [ "_$NVM_METHOD" = "_script" ]; then NVM_SOURCE_URL="https://raw.githubusercontent.com/creationix/nvm/$(nvm_latest_version)/nvm.sh" elif [ "_$NVM_METHOD" = "_git" ] || [ -z "$NVM_METHOD" ]; then NVM_SOURCE_URL="https://github.com/creationix/nvm.git" else echo >&2 "Unexpected value \"$NVM_METHOD\" for \$NVM_METHOD" return 1 fi fi echo "$NVM_SOURCE_URL" } nvm_download() { if nvm_has "curl"; then curl -q $* elif nvm_has "wget"; then # Emulate curl with wget ARGS=$(echo "$*" | command sed -e 's/--progress-bar /--progress=bar /' \ -e 's/-L //' \ -e 's/-I /--server-response /' \ -e 's/-s /-q /' \ -e 's/-o /-O /' \ -e 's/-C - /-c /') wget $ARGS fi } install_nvm_from_git() { if [ -d "$NVM_DIR/.git" ]; then echo "=> nvm is already installed in $NVM_DIR, trying to update using git" printf "\r=> " cd "$NVM_DIR" && (command git fetch 2> /dev/null || { echo >&2 "Failed to update nvm, run 'git fetch' in $NVM_DIR yourself." && exit 1 }) else # Cloning to $NVM_DIR echo "=> Downloading nvm from git to '$NVM_DIR'" printf "\r=> " mkdir -p "$NVM_DIR" command git clone "$(nvm_source git)" "$NVM_DIR" fi cd "$NVM_DIR" && command git checkout --quiet $(nvm_latest_version) if [ ! -z "$(cd "$NVM_DIR" && git show-ref refs/heads/master)" ]; then if git branch --quiet 2>/dev/null; then cd "$NVM_DIR" && command git branch --quiet -D master >/dev/null 2>&1 else echo >&2 "Your version of git is out of date. Please update it!" cd "$NVM_DIR" && command git branch -D master >/dev/null 2>&1 fi fi return } install_nvm_as_script() { local NVM_SOURCE_LOCAL NVM_SOURCE_LOCAL=$(nvm_source script) local NVM_EXEC_SOURCE NVM_EXEC_SOURCE=$(nvm_source script-nvm-exec) # Downloading to $NVM_DIR mkdir -p "$NVM_DIR" if [ -f "$NVM_DIR/nvm.sh" ]; then echo "=> nvm is already installed in $NVM_DIR, trying to update the script" else echo "=> Downloading nvm as script to '$NVM_DIR'" fi nvm_download -s "$NVM_SOURCE_LOCAL" -o "$NVM_DIR/nvm.sh" || { echo >&2 "Failed to download '$NVM_SOURCE_LOCAL'" return 1 } nvm_download -s "$NVM_EXEC_SOURCE" -o "$NVM_DIR/nvm-exec" || { echo >&2 "Failed to download '$NVM_EXEC_SOURCE'" return 2 } chmod a+x "$NVM_DIR/nvm-exec" || { echo >&2 "Failed to mark '$NVM_DIR/nvm-exec' as executable" return 3 } } # # Detect profile file if not specified as environment variable # (eg: PROFILE=~/.myprofile) # The echo'ed path is guaranteed to be an existing file # Otherwise, an empty string is returned # nvm_detect_profile() { local DETECTED_PROFILE DETECTED_PROFILE='' local SHELLTYPE SHELLTYPE="$(basename /$SHELL)" if [ $SHELLTYPE = "bash" ]; then if [ -f "$HOME/.bashrc" ]; then DETECTED_PROFILE="$HOME/.bashrc" elif [ -f "$HOME/.bash_profile" ]; then DETECTED_PROFILE="$HOME/.bash_profile" fi elif [ $SHELLTYPE = "zsh" ]; then DETECTED_PROFILE="$HOME/.zshrc" fi if [ -z "$DETECTED_PROFILE" ]; then if [ -f "$PROFILE" ]; then DETECTED_PROFILE="$PROFILE" elif [ -f "$HOME/.profile" ]; then DETECTED_PROFILE="$HOME/.profile" elif [ -f "$HOME/.bashrc" ]; then DETECTED_PROFILE="$HOME/.bashrc" elif [ -f "$HOME/.bash_profile" ]; then DETECTED_PROFILE="$HOME/.bash_profile" elif [ -f "$HOME/.zshrc" ]; then DETECTED_PROFILE="$HOME/.zshrc" fi fi if [ ! -z "$DETECTED_PROFILE" ]; then echo "$DETECTED_PROFILE" fi } # # Check whether the user has any globally-installed npm modules in their system # Node, and warn them if so. # nvm_check_global_modules() { command -v npm >/dev/null 2>&1 || return 0 local NPM_VERSION NPM_VERSION="$(npm --version)" NPM_VERSION="${NPM_VERSION:--1}" [ "${NPM_VERSION%%[!-0-9]*}" -gt 0 ] || return 0 local NPM_GLOBAL_MODULES NPM_GLOBAL_MODULES="$( npm list -g --depth=0 | sed '/ npm@/d' | sed '/ (empty)$/d' )" local MODULE_COUNT MODULE_COUNT="$( printf %s\\n "$NPM_GLOBAL_MODULES" | sed -ne '1!p' | # Remove the first line wc -l | tr -d ' ' # Count entries )" if [ $MODULE_COUNT -ne 0 ]; then cat <<-'END_MESSAGE' => You currently have modules installed globally with `npm`. These will no => longer be linked to the active version of Node when you install a new node => with `nvm`; and they may (depending on how you construct your `$PATH`) => override the binaries of modules installed with `nvm`: END_MESSAGE printf %s\\n "$NPM_GLOBAL_MODULES" cat <<-'END_MESSAGE' => If you wish to uninstall them at a later point (or re-install them under your => `nvm` Nodes), you can remove them from the system Node as follows: $ nvm use system $ npm uninstall -g a_module END_MESSAGE fi } nvm_do_install() { if [ -z "$METHOD" ]; then # Autodetect install method if nvm_has "git"; then install_nvm_from_git elif nvm_has "nvm_download"; then install_nvm_as_script else echo >&2 "You need git, curl, or wget to install nvm" exit 1 fi elif [ "~$METHOD" = "~git" ]; then if ! nvm_has "git"; then echo >&2 "You need git to install nvm" exit 1 fi install_nvm_from_git elif [ "~$METHOD" = "~script" ]; then if ! nvm_has "nvm_download"; then echo >&2 "You need curl or wget to install nvm" exit 1 fi install_nvm_as_script fi echo local NVM_PROFILE NVM_PROFILE=$(nvm_detect_profile) SOURCE_STR="\nexport NVM_DIR=\"$NVM_DIR\"\n[ -s \"\$NVM_DIR/nvm.sh\" ] && . \"\$NVM_DIR/nvm.sh\" # This loads nvm" if [ -z "$NVM_PROFILE" ] ; then echo "=> Profile not found. Tried $NVM_PROFILE (as defined in \$PROFILE), ~/.bashrc, ~/.bash_profile, ~/.zshrc, and ~/.profile." echo "=> Create one of them and run this script again" echo "=> Create it (touch $NVM_PROFILE) and run this script again" echo " OR" echo "=> Append the following lines to the correct file yourself:" printf "$SOURCE_STR" echo else if ! command grep -qc '/nvm.sh' "$NVM_PROFILE"; then echo "=> Appending source string to $NVM_PROFILE" printf "$SOURCE_STR\n" >> "$NVM_PROFILE" else echo "=> Source string already in $NVM_PROFILE" fi fi nvm_check_global_modules echo "=> Close and reopen your terminal to start using nvm" nvm_reset } # # Unsets the various functions defined # during the execution of the install script # nvm_reset() { unset -f nvm_reset nvm_has nvm_latest_version \ nvm_source nvm_download install_nvm_as_script install_nvm_from_git \ nvm_detect_profile nvm_check_global_modules nvm_do_install } [ "_$NVM_ENV" = "_testing" ] || nvm_do_install } # this ensures the entire script is downloaded #
dylanlott/bridge-gui
ansible/roles/node/files/nvm-v0.30.1-install.sh
Shell
agpl-3.0
7,735
# Vitral A backend-agnostic immediate mode GUI library. ## Working with raw font files Using ImageMagick, convert raw font to png: convert -depth 8 -size 96x48 a:src/font-96x48.raw font.png Convert png back to raw: convert font.png a:src/font-96x48.raw (The size value depends on the dimensions of your font sheet.)
rsaarelm/magog
vitral/README.md
Markdown
agpl-3.0
331
/****************************************************************************** * $Id: gt_overview.cpp 21799 2011-02-22 21:25:59Z warmerdam $ * * Project: GeoTIFF Driver * Purpose: Code to build overviews of external databases as a TIFF file. * Only used by the GDALDefaultOverviews::BuildOverviews() method. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 2000, Frank Warmerdam * * 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 "gdal_priv.h" #define CPL_SERV_H_INCLUDED #include "xtiffio.h" #include "gt_overview.h" #include "gtiff.h" CPL_CVSID("$Id: gt_overview.cpp 21799 2011-02-22 21:25:59Z warmerdam $"); /************************************************************************/ /* GTIFFWriteDirectory() */ /* */ /* Create a new directory, without any image data for an overview */ /* or a mask */ /* Returns offset of newly created directory, but the */ /* current directory is reset to be the one in used when this */ /* function is called. */ /************************************************************************/ toff_t GTIFFWriteDirectory(TIFF *hTIFF, int nSubfileType, int nXSize, int nYSize, int nBitsPerPixel, int nPlanarConfig, int nSamples, int nBlockXSize, int nBlockYSize, int bTiled, int nCompressFlag, int nPhotometric, int nSampleFormat, int nPredictor, unsigned short *panRed, unsigned short *panGreen, unsigned short *panBlue, int nExtraSamples, unsigned short *panExtraSampleValues, const char *pszMetadata ) { toff_t nBaseDirOffset; toff_t nOffset; nBaseDirOffset = TIFFCurrentDirOffset( hTIFF ); #if defined(TIFFLIB_VERSION) && TIFFLIB_VERSION >= 20051201 /* 3.8.0 */ TIFFFreeDirectory( hTIFF ); #endif TIFFCreateDirectory( hTIFF ); /* -------------------------------------------------------------------- */ /* Setup TIFF fields. */ /* -------------------------------------------------------------------- */ TIFFSetField( hTIFF, TIFFTAG_IMAGEWIDTH, nXSize ); TIFFSetField( hTIFF, TIFFTAG_IMAGELENGTH, nYSize ); if( nSamples == 1 ) TIFFSetField( hTIFF, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG ); else TIFFSetField( hTIFF, TIFFTAG_PLANARCONFIG, nPlanarConfig ); TIFFSetField( hTIFF, TIFFTAG_BITSPERSAMPLE, nBitsPerPixel ); TIFFSetField( hTIFF, TIFFTAG_SAMPLESPERPIXEL, nSamples ); TIFFSetField( hTIFF, TIFFTAG_COMPRESSION, nCompressFlag ); TIFFSetField( hTIFF, TIFFTAG_PHOTOMETRIC, nPhotometric ); TIFFSetField( hTIFF, TIFFTAG_SAMPLEFORMAT, nSampleFormat ); if( bTiled ) { TIFFSetField( hTIFF, TIFFTAG_TILEWIDTH, nBlockXSize ); TIFFSetField( hTIFF, TIFFTAG_TILELENGTH, nBlockYSize ); } else TIFFSetField( hTIFF, TIFFTAG_ROWSPERSTRIP, nBlockYSize ); TIFFSetField( hTIFF, TIFFTAG_SUBFILETYPE, nSubfileType ); if (panExtraSampleValues != NULL) { TIFFSetField(hTIFF, TIFFTAG_EXTRASAMPLES, nExtraSamples, panExtraSampleValues ); } if ( nCompressFlag == COMPRESSION_LZW || nCompressFlag == COMPRESSION_ADOBE_DEFLATE ) TIFFSetField( hTIFF, TIFFTAG_PREDICTOR, nPredictor ); /* -------------------------------------------------------------------- */ /* Write color table if one is present. */ /* -------------------------------------------------------------------- */ if( panRed != NULL ) { TIFFSetField( hTIFF, TIFFTAG_COLORMAP, panRed, panGreen, panBlue ); } /* -------------------------------------------------------------------- */ /* Write metadata if we have some. */ /* -------------------------------------------------------------------- */ if( pszMetadata && strlen(pszMetadata) > 0 ) TIFFSetField( hTIFF, TIFFTAG_GDAL_METADATA, pszMetadata ); /* -------------------------------------------------------------------- */ /* Write directory, and return byte offset. */ /* -------------------------------------------------------------------- */ if( TIFFWriteCheck( hTIFF, bTiled, "GTIFFWriteDirectory" ) == 0 ) { TIFFSetSubDirectory( hTIFF, nBaseDirOffset ); return 0; } TIFFWriteDirectory( hTIFF ); TIFFSetDirectory( hTIFF, (tdir_t) (TIFFNumberOfDirectories(hTIFF)-1) ); nOffset = TIFFCurrentDirOffset( hTIFF ); TIFFSetSubDirectory( hTIFF, nBaseDirOffset ); return nOffset; } /************************************************************************/ /* GTIFFBuildOverviewMetadata() */ /************************************************************************/ void GTIFFBuildOverviewMetadata( const char *pszResampling, GDALDataset *poBaseDS, CPLString &osMetadata ) { osMetadata = "<GDALMetadata>"; if( pszResampling && EQUALN(pszResampling,"AVERAGE_BIT2",12) ) osMetadata += "<Item name=\"RESAMPLING\" sample=\"0\">AVERAGE_BIT2GRAYSCALE</Item>"; if( poBaseDS->GetMetadataItem( "INTERNAL_MASK_FLAGS_1" ) ) { int iBand; for( iBand = 0; iBand < 200; iBand++ ) { CPLString osItem; CPLString osName; osName.Printf( "INTERNAL_MASK_FLAGS_%d", iBand+1 ); if( poBaseDS->GetMetadataItem( osName ) ) { osItem.Printf( "<Item name=\"%s\">%s</Item>", osName.c_str(), poBaseDS->GetMetadataItem( osName ) ); osMetadata += osItem; } } } const char* pszNoDataValues = poBaseDS->GetMetadataItem("NODATA_VALUES"); if (pszNoDataValues) { CPLString osItem; osItem.Printf( "<Item name=\"NODATA_VALUES\">%s</Item>", pszNoDataValues ); osMetadata += osItem; } if( !EQUAL(osMetadata,"<GDALMetadata>") ) osMetadata += "</GDALMetadata>"; else osMetadata = ""; } /************************************************************************/ /* GTIFFBuildOverviews() */ /************************************************************************/ CPLErr GTIFFBuildOverviews( const char * pszFilename, int nBands, GDALRasterBand **papoBandList, int nOverviews, int * panOverviewList, const char * pszResampling, GDALProgressFunc pfnProgress, void * pProgressData ) { TIFF *hOTIFF; int nBitsPerPixel=0, nCompression=COMPRESSION_NONE, nPhotometric=0; int nSampleFormat=0, nPlanarConfig, iOverview, iBand; int nXSize=0, nYSize=0; if( nBands == 0 || nOverviews == 0 ) return CE_None; if (!GTiffOneTimeInit()) return CE_Failure; /* -------------------------------------------------------------------- */ /* Verify that the list of bands is suitable for emitting in */ /* TIFF file. */ /* -------------------------------------------------------------------- */ for( iBand = 0; iBand < nBands; iBand++ ) { int nBandBits, nBandFormat; GDALRasterBand *hBand = papoBandList[iBand]; switch( hBand->GetRasterDataType() ) { case GDT_Byte: nBandBits = 8; nBandFormat = SAMPLEFORMAT_UINT; break; case GDT_UInt16: nBandBits = 16; nBandFormat = SAMPLEFORMAT_UINT; break; case GDT_Int16: nBandBits = 16; nBandFormat = SAMPLEFORMAT_INT; break; case GDT_UInt32: nBandBits = 32; nBandFormat = SAMPLEFORMAT_UINT; break; case GDT_Int32: nBandBits = 32; nBandFormat = SAMPLEFORMAT_INT; break; case GDT_Float32: nBandBits = 32; nBandFormat = SAMPLEFORMAT_IEEEFP; break; case GDT_Float64: nBandBits = 64; nBandFormat = SAMPLEFORMAT_IEEEFP; break; case GDT_CInt16: nBandBits = 32; nBandFormat = SAMPLEFORMAT_COMPLEXINT; break; case GDT_CInt32: nBandBits = 64; nBandFormat = SAMPLEFORMAT_COMPLEXINT; break; case GDT_CFloat32: nBandBits = 64; nBandFormat = SAMPLEFORMAT_COMPLEXIEEEFP; break; case GDT_CFloat64: nBandBits = 128; nBandFormat = SAMPLEFORMAT_COMPLEXIEEEFP; break; default: CPLAssert( FALSE ); return CE_Failure; } if( hBand->GetMetadataItem( "NBITS", "IMAGE_STRUCTURE" ) ) { nBandBits = atoi(hBand->GetMetadataItem("NBITS","IMAGE_STRUCTURE")); if( nBandBits == 1 && EQUALN(pszResampling,"AVERAGE_BIT2",12) ) nBandBits = 8; } if( iBand == 0 ) { nBitsPerPixel = nBandBits; nSampleFormat = nBandFormat; nXSize = hBand->GetXSize(); nYSize = hBand->GetYSize(); } else if( nBitsPerPixel != nBandBits || nSampleFormat != nBandFormat ) { CPLError( CE_Failure, CPLE_NotSupported, "GTIFFBuildOverviews() doesn't support a mixture of band" " data types." ); return CE_Failure; } else if( hBand->GetColorTable() != NULL ) { CPLError( CE_Failure, CPLE_NotSupported, "GTIFFBuildOverviews() doesn't support building" " overviews of multiple colormapped bands." ); return CE_Failure; } else if( hBand->GetXSize() != nXSize || hBand->GetYSize() != nYSize ) { CPLError( CE_Failure, CPLE_NotSupported, "GTIFFBuildOverviews() doesn't support building" " overviews of different sized bands." ); return CE_Failure; } } /* -------------------------------------------------------------------- */ /* Use specified compression method. */ /* -------------------------------------------------------------------- */ const char *pszCompress = CPLGetConfigOption( "COMPRESS_OVERVIEW", NULL ); if( pszCompress != NULL && pszCompress[0] != '\0' ) { nCompression = GTIFFGetCompressionMethod(pszCompress, "COMPRESS_OVERVIEW"); if (nCompression < 0) return CE_Failure; } if( nCompression == COMPRESSION_JPEG && nBitsPerPixel > 8 ) { if( nBitsPerPixel > 16 ) { CPLError( CE_Failure, CPLE_NotSupported, "GTIFFBuildOverviews() doesn't support building" " JPEG compressed overviews of nBitsPerPixel > 16." ); return CE_Failure; } nBitsPerPixel = 12; } /* -------------------------------------------------------------------- */ /* Figure out the planar configuration to use. */ /* -------------------------------------------------------------------- */ if( nBands == 1 ) nPlanarConfig = PLANARCONFIG_CONTIG; else nPlanarConfig = PLANARCONFIG_SEPARATE; const char* pszInterleave = CPLGetConfigOption( "INTERLEAVE_OVERVIEW", NULL ); if (pszInterleave != NULL && pszInterleave[0] != '\0') { if( EQUAL( pszInterleave, "PIXEL" ) ) nPlanarConfig = PLANARCONFIG_CONTIG; else if( EQUAL( pszInterleave, "BAND" ) ) nPlanarConfig = PLANARCONFIG_SEPARATE; else { CPLError( CE_Failure, CPLE_AppDefined, "INTERLEAVE_OVERVIEW=%s unsupported, value must be PIXEL or BAND. ignoring", pszInterleave ); } } /* -------------------------------------------------------------------- */ /* Figure out the photometric interpretation to use. */ /* -------------------------------------------------------------------- */ if( nBands == 3 ) nPhotometric = PHOTOMETRIC_RGB; else if( papoBandList[0]->GetColorTable() != NULL && !EQUALN(pszResampling,"AVERAGE_BIT2",12) ) { nPhotometric = PHOTOMETRIC_PALETTE; /* should set the colormap up at this point too! */ } else nPhotometric = PHOTOMETRIC_MINISBLACK; const char* pszPhotometric = CPLGetConfigOption( "PHOTOMETRIC_OVERVIEW", NULL ); if (pszPhotometric != NULL && pszPhotometric[0] != '\0') { if( EQUAL( pszPhotometric, "MINISBLACK" ) ) nPhotometric = PHOTOMETRIC_MINISBLACK; else if( EQUAL( pszPhotometric, "MINISWHITE" ) ) nPhotometric = PHOTOMETRIC_MINISWHITE; else if( EQUAL( pszPhotometric, "RGB" )) { nPhotometric = PHOTOMETRIC_RGB; } else if( EQUAL( pszPhotometric, "CMYK" )) { nPhotometric = PHOTOMETRIC_SEPARATED; } else if( EQUAL( pszPhotometric, "YCBCR" )) { nPhotometric = PHOTOMETRIC_YCBCR; /* Because of subsampling, setting YCBCR without JPEG compression leads */ /* to a crash currently. Would need to make GTiffRasterBand::IWriteBlock() */ /* aware of subsampling so that it doesn't overrun buffer size returned */ /* by libtiff */ if ( nCompression != COMPRESSION_JPEG ) { CPLError(CE_Failure, CPLE_NotSupported, "Currently, PHOTOMETRIC_OVERVIEW=YCBCR requires COMPRESS_OVERVIEW=JPEG"); return CE_Failure; } if (pszInterleave != NULL && pszInterleave[0] != '\0' && nPlanarConfig == PLANARCONFIG_SEPARATE) { CPLError(CE_Failure, CPLE_NotSupported, "PHOTOMETRIC_OVERVIEW=YCBCR requires INTERLEAVE_OVERVIEW=PIXEL"); return CE_Failure; } else { nPlanarConfig = PLANARCONFIG_CONTIG; } /* YCBCR strictly requires 3 bands. Not less, not more */ /* Issue an explicit error message as libtiff one is a bit cryptic : */ /* JPEGLib:Bogus input colorspace */ if ( nBands != 3 ) { CPLError(CE_Failure, CPLE_NotSupported, "PHOTOMETRIC_OVERVIEW=YCBCR requires a source raster with only 3 bands (RGB)"); return CE_Failure; } } else if( EQUAL( pszPhotometric, "CIELAB" )) { nPhotometric = PHOTOMETRIC_CIELAB; } else if( EQUAL( pszPhotometric, "ICCLAB" )) { nPhotometric = PHOTOMETRIC_ICCLAB; } else if( EQUAL( pszPhotometric, "ITULAB" )) { nPhotometric = PHOTOMETRIC_ITULAB; } else { CPLError( CE_Warning, CPLE_IllegalArg, "PHOTOMETRIC_OVERVIEW=%s value not recognised, ignoring.\n", pszPhotometric ); } } /* -------------------------------------------------------------------- */ /* Figure out the predictor value to use. */ /* -------------------------------------------------------------------- */ int nPredictor = PREDICTOR_NONE; if ( nCompression == COMPRESSION_LZW || nCompression == COMPRESSION_ADOBE_DEFLATE ) { const char* pszPredictor = CPLGetConfigOption( "PREDICTOR_OVERVIEW", NULL ); if( pszPredictor != NULL ) { nPredictor = atoi( pszPredictor ); } } /* -------------------------------------------------------------------- */ /* Create the file, if it does not already exist. */ /* -------------------------------------------------------------------- */ VSIStatBufL sStatBuf; if( VSIStatExL( pszFilename, &sStatBuf, VSI_STAT_EXISTS_FLAG ) != 0 ) { /* -------------------------------------------------------------------- */ /* Compute the uncompressed size. */ /* -------------------------------------------------------------------- */ double dfUncompressedOverviewSize = 0; int nDataTypeSize = GDALGetDataTypeSize(papoBandList[0]->GetRasterDataType())/8; for( iOverview = 0; iOverview < nOverviews; iOverview++ ) { int nOXSize, nOYSize; nOXSize = (nXSize + panOverviewList[iOverview] - 1) / panOverviewList[iOverview]; nOYSize = (nYSize + panOverviewList[iOverview] - 1) / panOverviewList[iOverview]; dfUncompressedOverviewSize += nOXSize * ((double)nOYSize) * nBands * nDataTypeSize; } if( nCompression == COMPRESSION_NONE && dfUncompressedOverviewSize > 4200000000.0 ) { #ifndef BIGTIFF_SUPPORT CPLError( CE_Failure, CPLE_NotSupported, "The overview file would be larger than 4GB\n" "but this is the largest size a TIFF can be, and BigTIFF is unavailable.\n" "Creation failed." ); return CE_Failure; #endif } /* -------------------------------------------------------------------- */ /* Should the file be created as a bigtiff file? */ /* -------------------------------------------------------------------- */ const char *pszBIGTIFF = CPLGetConfigOption( "BIGTIFF_OVERVIEW", NULL ); if( pszBIGTIFF == NULL ) pszBIGTIFF = "IF_NEEDED"; int bCreateBigTIFF = FALSE; if( EQUAL(pszBIGTIFF,"IF_NEEDED") ) { if( nCompression == COMPRESSION_NONE && dfUncompressedOverviewSize > 4200000000.0 ) bCreateBigTIFF = TRUE; } else if( EQUAL(pszBIGTIFF,"IF_SAFER") ) { /* Look at the size of the base image and suppose that */ /* the added overview levels won't be more than 1/2 of */ /* the size of the base image. The theory says 1/3 of the */ /* base image size if the overview levels are 2, 4, 8, 16... */ /* Thus take 1/2 as the security margin for 1/3 */ double dfUncompressedImageSize = nXSize * ((double)nYSize) * nBands * nDataTypeSize; if( dfUncompressedImageSize * .5 > 4200000000.0 ) bCreateBigTIFF = TRUE; } else { bCreateBigTIFF = CSLTestBoolean( pszBIGTIFF ); if (!bCreateBigTIFF && nCompression == COMPRESSION_NONE && dfUncompressedOverviewSize > 4200000000.0 ) { CPLError( CE_Failure, CPLE_NotSupported, "The overview file will be larger than 4GB, so BigTIFF is necessary.\n" "Creation failed."); return CE_Failure; } } #ifndef BIGTIFF_SUPPORT if( bCreateBigTIFF ) { CPLError( CE_Warning, CPLE_NotSupported, "BigTIFF requested, but GDAL built without BigTIFF\n" "enabled libtiff, request ignored." ); bCreateBigTIFF = FALSE; } #endif if( bCreateBigTIFF ) CPLDebug( "GTiff", "File being created as a BigTIFF." ); hOTIFF = XTIFFOpen( pszFilename, (bCreateBigTIFF) ? "w+8" : "w+" ); if( hOTIFF == NULL ) { if( CPLGetLastErrorNo() == 0 ) CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create new tiff file `%s'\n" "failed in XTIFFOpen().\n", pszFilename ); return CE_Failure; } } /* -------------------------------------------------------------------- */ /* Otherwise just open it for update access. */ /* -------------------------------------------------------------------- */ else { hOTIFF = XTIFFOpen( pszFilename, "r+" ); if( hOTIFF == NULL ) { if( CPLGetLastErrorNo() == 0 ) CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create new tiff file `%s'\n" "failed in XTIFFOpen().\n", pszFilename ); return CE_Failure; } } /* -------------------------------------------------------------------- */ /* Do we have a palette? If so, create a TIFF compatible version. */ /* -------------------------------------------------------------------- */ unsigned short *panRed=NULL, *panGreen=NULL, *panBlue=NULL; if( nPhotometric == PHOTOMETRIC_PALETTE ) { GDALColorTable *poCT = papoBandList[0]->GetColorTable(); int nColorCount; if( nBitsPerPixel <= 8 ) nColorCount = 256; else nColorCount = 65536; panRed = (unsigned short *) CPLCalloc(nColorCount,sizeof(unsigned short)); panGreen = (unsigned short *) CPLCalloc(nColorCount,sizeof(unsigned short)); panBlue = (unsigned short *) CPLCalloc(nColorCount,sizeof(unsigned short)); for( int iColor = 0; iColor < nColorCount; iColor++ ) { GDALColorEntry sRGB; if( poCT->GetColorEntryAsRGB( iColor, &sRGB ) ) { panRed[iColor] = (unsigned short) (257 * sRGB.c1); panGreen[iColor] = (unsigned short) (257 * sRGB.c2); panBlue[iColor] = (unsigned short) (257 * sRGB.c3); } } } /* -------------------------------------------------------------------- */ /* Do we need some metadata for the overviews? */ /* -------------------------------------------------------------------- */ CPLString osMetadata; GDALDataset *poBaseDS = papoBandList[0]->GetDataset(); GTIFFBuildOverviewMetadata( pszResampling, poBaseDS, osMetadata ); /* -------------------------------------------------------------------- */ /* Loop, creating overviews. */ /* -------------------------------------------------------------------- */ int nOvrBlockXSize, nOvrBlockYSize; GTIFFGetOverviewBlockSize(&nOvrBlockXSize, &nOvrBlockYSize); for( iOverview = 0; iOverview < nOverviews; iOverview++ ) { int nOXSize, nOYSize; nOXSize = (nXSize + panOverviewList[iOverview] - 1) / panOverviewList[iOverview]; nOYSize = (nYSize + panOverviewList[iOverview] - 1) / panOverviewList[iOverview]; GTIFFWriteDirectory(hOTIFF, FILETYPE_REDUCEDIMAGE, nOXSize, nOYSize, nBitsPerPixel, nPlanarConfig, nBands, nOvrBlockXSize, nOvrBlockYSize, TRUE, nCompression, nPhotometric, nSampleFormat, nPredictor, panRed, panGreen, panBlue, 0, NULL, /* FIXME? how can we fetch extrasamples */ osMetadata ); } if (panRed) { CPLFree(panRed); CPLFree(panGreen); CPLFree(panBlue); panRed = panGreen = panBlue = NULL; } XTIFFClose( hOTIFF ); /* -------------------------------------------------------------------- */ /* Open the overview dataset so that we can get at the overview */ /* bands. */ /* -------------------------------------------------------------------- */ GDALDataset *hODS; CPLErr eErr = CE_None; hODS = (GDALDataset *) GDALOpen( pszFilename, GA_Update ); if( hODS == NULL ) return CE_Failure; /* -------------------------------------------------------------------- */ /* Do we need to set the jpeg quality? */ /* -------------------------------------------------------------------- */ TIFF *hTIFF = (TIFF*) hODS->GetInternalHandle(NULL); if( nCompression == COMPRESSION_JPEG && CPLGetConfigOption( "JPEG_QUALITY_OVERVIEW", NULL ) != NULL ) { int nJpegQuality = atoi(CPLGetConfigOption("JPEG_QUALITY_OVERVIEW","75")); TIFFSetField( hTIFF, TIFFTAG_JPEGQUALITY, nJpegQuality ); GTIFFSetJpegQuality((GDALDatasetH)hODS, nJpegQuality); } /* -------------------------------------------------------------------- */ /* Loop writing overview data. */ /* -------------------------------------------------------------------- */ if (nCompression != COMPRESSION_NONE && nPlanarConfig == PLANARCONFIG_CONTIG && GDALDataTypeIsComplex(papoBandList[0]->GetRasterDataType()) == FALSE && papoBandList[0]->GetColorTable() == NULL && (EQUALN(pszResampling, "NEAR", 4) || EQUAL(pszResampling, "AVERAGE") || EQUAL(pszResampling, "GAUSS"))) { /* In the case of pixel interleaved compressed overviews, we want to generate */ /* the overviews for all the bands block by block, and not band after band, */ /* in order to write the block once and not loose space in the TIFF file */ GDALRasterBand ***papapoOverviewBands; papapoOverviewBands = (GDALRasterBand ***) CPLCalloc(sizeof(void*),nBands); for( iBand = 0; iBand < nBands && eErr == CE_None; iBand++ ) { GDALRasterBand *hDstBand = hODS->GetRasterBand( iBand+1 ); papapoOverviewBands[iBand] = (GDALRasterBand **) CPLCalloc(sizeof(void*),nOverviews); papapoOverviewBands[iBand][0] = hDstBand; for( int i = 0; i < nOverviews-1 && eErr == CE_None; i++ ) { papapoOverviewBands[iBand][i+1] = hDstBand->GetOverview(i); if (papapoOverviewBands[iBand][i+1] == NULL) eErr = CE_Failure; } } if (eErr == CE_None) eErr = GDALRegenerateOverviewsMultiBand(nBands, papoBandList, nOverviews, papapoOverviewBands, pszResampling, pfnProgress, pProgressData ); for( iBand = 0; iBand < nBands; iBand++ ) { CPLFree(papapoOverviewBands[iBand]); } CPLFree(papapoOverviewBands); } else { GDALRasterBand **papoOverviews; papoOverviews = (GDALRasterBand **) CPLCalloc(sizeof(void*),128); for( iBand = 0; iBand < nBands && eErr == CE_None; iBand++ ) { GDALRasterBand *hSrcBand = papoBandList[iBand]; GDALRasterBand *hDstBand; int nDstOverviews; hDstBand = hODS->GetRasterBand( iBand+1 ); papoOverviews[0] = hDstBand; nDstOverviews = hDstBand->GetOverviewCount() + 1; CPLAssert( nDstOverviews < 128 ); nDstOverviews = MIN(128,nDstOverviews); for( int i = 0; i < nDstOverviews-1 && eErr == CE_None; i++ ) { papoOverviews[i+1] = hDstBand->GetOverview(i); if (papoOverviews[i+1] == NULL) eErr = CE_Failure; } void *pScaledProgressData; pScaledProgressData = GDALCreateScaledProgress( iBand / (double) nBands, (iBand+1) / (double) nBands, pfnProgress, pProgressData ); if (eErr == CE_None) eErr = GDALRegenerateOverviews( (GDALRasterBandH) hSrcBand, nDstOverviews, (GDALRasterBandH *) papoOverviews, pszResampling, GDALScaledProgress, pScaledProgressData); GDALDestroyScaledProgress( pScaledProgressData ); } CPLFree( papoOverviews ); } /* -------------------------------------------------------------------- */ /* Cleanup */ /* -------------------------------------------------------------------- */ if (eErr == CE_None) hODS->FlushCache(); delete hODS; pfnProgress( 1.0, NULL, pProgressData ); return eErr; }
AsherBond/MondocosmOS
gdal/frmts/gtiff/gt_overview.cpp
C++
agpl-3.0
30,706
using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Serialization; namespace MLAgents { [Serializable] public class ResetParameters : Dictionary<string, float>, ISerializationCallbackReceiver { [Serializable] public struct ResetParameter { public string key; public float value; } [FormerlySerializedAs("resetParameters")] [SerializeField] private List<ResetParameter> m_ResetParameters = new List<ResetParameter>(); public void OnBeforeSerialize() { m_ResetParameters.Clear(); foreach (var pair in this) { var rp = new ResetParameter(); rp.key = pair.Key; rp.value = pair.Value; m_ResetParameters.Add(rp); } } public void OnAfterDeserialize() { Clear(); for (var i = 0; i < m_ResetParameters.Count; i++) { if (ContainsKey(m_ResetParameters[i].key)) { Debug.LogError("The ResetParameters contains the same key twice"); } else { Add(m_ResetParameters[i].key, m_ResetParameters[i].value); } } } } }
Necromunger/unitystation
UnityProject/Assets/ML-Agents/Scripts/ResetParameters.cs
C#
agpl-3.0
1,370
/* * Copyright (C) 2011-2012 DarkCore <http://www.darkpeninsula.eu/> * Copyright (C) 2011-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/> * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef DEF_ARCHAVON_H #define DEF_ARCHAVON_H enum Creatures { CREATURE_ARCHAVON = 31125, CREATURE_EMALON = 33993, CREATURE_KORALON = 35013, CREATURE_TORAVON = 38433, }; enum Data { DATA_ARCHAVON = 0, DATA_EMALON = 1, DATA_KORALON = 2, DATA_TORAVON = 3, }; #define MAX_ENCOUNTER 4 enum AchievementCriteriaIds { CRITERIA_EARTH_WIND_FIRE_10 = 12018, CRITERIA_EARTH_WIND_FIRE_25 = 12019, }; enum AchievementSpells { SPELL_EARTH_WIND_FIRE_ACHIEVEMENT_CHECK = 68308, }; #endif
Darkpeninsula/Darkcore
src/server/scripts/Northrend/VaultOfArchavon/vault_of_archavon.h
C
agpl-3.0
1,564
// This file may be edited manually or auto-generated using IfcKit at www.buildingsmart-tech.org. // IFC content is copyright (C) 1996-2018 BuildingSMART International Ltd. using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Xml.Serialization; namespace BuildingSmart.IFC.IfcStructuralAnalysisDomain { public enum IfcActionTypeEnum { PERMANENT_G = 1, VARIABLE_Q = 2, EXTRAORDINARY_A = 3, USERDEFINED = -1, NOTDEFINED = 0, } }
pipauwel/IfcDoc
IfcKit/schemas/IfcStructuralAnalysisDomain/IfcActionTypeEnum.cs
C#
agpl-3.0
661
/******************************************************************************* * HELIUM V, Open Source ERP software for sustained success * at small and medium-sized enterprises. * Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of theLicense, or * (at your option) any later version. * * According to sec. 7 of the GNU Affero General Public License, version 3, * the terms of the AGPL are supplemented with the following terms: * * "HELIUM V" and "HELIUM 5" are registered trademarks of * HELIUM V IT-Solutions GmbH. The licensing of the program under the * AGPL does not imply a trademark license. Therefore any rights, title and * interest in our trademarks remain entirely with us. If you want to propagate * modified versions of the Program under the name "HELIUM V" or "HELIUM 5", * you may only do so if you have a written permission by HELIUM V IT-Solutions * GmbH (to acquire a permission please contact HELIUM V IT-Solutions * at trademark@heliumv.com). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact: developers@heliumv.com ******************************************************************************/ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.01.30 at 04:44:14 PM MEZ // package com.lp.server.schema.bmecat_2005; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;simpleContent> * &lt;restriction base="&lt;http://www.bmecat.org/bmecat/2005>dtMLSTRING"> * &lt;/restriction> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "EXEMPTION_REASON") public class BCEXEMPTIONREASON extends DtMLSTRING { }
erdincay/ejb
src/com/lp/server/schema/bmecat_2005/BCEXEMPTIONREASON.java
Java
agpl-3.0
2,854
var OncoprintTrackOptionsView = (function() { function OncoprintTrackOptionsView($div, moveUpCallback, moveDownCallback, removeCallback, sortChangeCallback) { // removeCallback: function(track_id) var position = $div.css('position'); if (position !== 'absolute' && position !=='relative') { console.log("WARNING: div passed to OncoprintTrackOptionsView must be absolute or relative positioned - layout problems will occur"); } this.moveUpCallback = moveUpCallback; this.moveDownCallback = moveDownCallback; this.removeCallback = removeCallback; // function(track_id) { ... } this.sortChangeCallback = sortChangeCallback; // function(track_id, dir) { ... } this.$div = $div; this.img_size; this.rendering_suppressed = false; this.track_options_$elts = {}; this.menu_shown = {}; var self = this; $(document).click(function () { for (var track_id in self.track_options_$elts) { if (self.track_options_$elts.hasOwnProperty(track_id)) { hideTrackMenu(self, track_id); } } }); this.interaction_disabled = false; } var renderAllOptions = function(view, model) { if (this.rendering_suppressed) { return; } view.$div.empty(); var tracks = model.getTracks(); var minimum_track_height = Number.POSITIVE_INFINITY; for (var i=0; i<tracks.length; i++) { minimum_track_height = Math.min(minimum_track_height, model.getTrackHeight(tracks[i])); } view.img_size = Math.floor(minimum_track_height*0.75); for (var i=0; i<tracks.length; i++) { renderTrackOptions(view, model, tracks[i]); } }; var hideTrackMenu = function(view, track_id) { view.menu_shown[track_id] = false; var $elts = view.track_options_$elts[track_id]; $elts.$div.css({'z-index': 1}); $elts.$dropdown.css({'border': '1px solid rgba(125,125,125,0)'}); $elts.$img.css({'border': '1px solid rgba(125,125,125,0)'}); $elts.$dropdown.fadeOut(100); }; var showTrackMenu = function(view, track_id) { view.menu_shown[track_id] = true; var $elts = view.track_options_$elts[track_id]; $elts.$div.css({'z-index': 10}); $elts.$dropdown.css({'border': '1px solid rgba(125,125,125,1)'}); $elts.$img.css({'border': '1px solid rgba(125,125,125,1)'}); $elts.$dropdown.fadeIn(100); }; var hideMenusExcept = function(view, track_id) { track_id = track_id.toString(); for (var other_track_id in view.track_options_$elts) { if (view.track_options_$elts.hasOwnProperty(other_track_id)) { if (other_track_id === track_id) { continue; } hideTrackMenu(view, other_track_id); } } }; var $makeDropdownOption = function(text, weight, callback) { return $('<li>').text(text).css({'font-weight': weight, 'font-size': 12, 'cursor': 'pointer', 'border-bottom':'1px solid rgba(0,0,0,0.3)'}) .click(callback) .hover(function () { $(this).css({'background-color': 'rgb(200,200,200)'}); }, function () { $(this).css({'background-color': 'rgba(255,255,255,0)'}); }); }; var $makeDropdownSeparator = function() { return $('<li>').css({'border-top': '1px solid black'}); }; var renderTrackOptions = function(view, model, track_id) { var $div,$img,$dropdown; //if (model.isTrackRemovable(track_id) || model.isTrackSortDirectionChangeable(track_id)) { $div = $('<div>').appendTo(view.$div).css({'position': 'absolute', 'left': '0px', 'top': model.getTrackTops(track_id) + 'px'}); $img = $('<img/>').appendTo($div).attr({'src': 'images/menudots.svg', 'width': view.img_size, 'height': view.img_size, 'alt': 'Track options'}).css({'float': 'left', 'cursor': 'pointer', 'border': '1px solid rgba(125,125,125,0)'}); $dropdown = $('<ul>').appendTo($div).css({'width': 120, 'display': 'none', 'list-style-type': 'none', 'padding-left': '6', 'padding-right': '6', 'float': 'right', 'background-color': 'rgb(255,255,255)'}); view.track_options_$elts[track_id] = {'$div': $div, '$img': $img, '$dropdown': $dropdown}; $img.hover(function(evt) { if (!view.menu_shown[track_id]) { $(this).css({'border': '1px solid rgba(125,125,125,0.3)'}); } }, function(evt) { if (!view.menu_shown[track_id]) { $(this).css({'border': '1px solid rgba(125,125,125,0)'}); } }); $img.click(function(evt) { evt.stopPropagation(); if ($dropdown.is(":visible")) { hideTrackMenu(view, track_id); } else { showTrackMenu(view, track_id); } hideMenusExcept(view, track_id); }); //} $dropdown.append($makeDropdownOption('Move up', 'normal', function(evt) { evt.stopPropagation(); view.moveUpCallback(track_id); })); $dropdown.append($makeDropdownOption('Move down', 'normal', function(evt) { evt.stopPropagation(); view.moveDownCallback(track_id); })); if (model.isTrackRemovable(track_id)) { $dropdown.append($makeDropdownOption('Remove track', 'normal', function(evt) { evt.stopPropagation(); view.removeCallback(track_id); })); } if (model.isTrackSortDirectionChangeable(track_id)) { $dropdown.append($makeDropdownSeparator()); var $sort_inc_li; var $sort_dec_li; var $dont_sort_li; $sort_inc_li = $makeDropdownOption('Sort a-Z', (model.getTrackSortDirection(track_id) === 1 ? 'bold' : 'normal'), function(evt) { evt.stopPropagation(); $sort_inc_li.css('font-weight', 'bold'); $sort_dec_li.css('font-weight', 'normal'); $dont_sort_li.css('font-weight', 'normal'); view.sortChangeCallback(track_id, 1); }); $sort_dec_li = $makeDropdownOption('Sort Z-a', (model.getTrackSortDirection(track_id) === -1 ? 'bold' : 'normal'), function(evt) { evt.stopPropagation(); $sort_inc_li.css('font-weight', 'normal'); $sort_dec_li.css('font-weight', 'bold'); $dont_sort_li.css('font-weight', 'normal'); view.sortChangeCallback(track_id, -1); }); $dont_sort_li = $makeDropdownOption('Don\'t sort track', (model.getTrackSortDirection(track_id) === 0 ? 'bold' : 'normal'), function(evt) { evt.stopPropagation(); $sort_inc_li.css('font-weight', 'normal'); $sort_dec_li.css('font-weight', 'normal'); $dont_sort_li.css('font-weight', 'bold'); view.sortChangeCallback(track_id, 0); }); $dropdown.append($sort_inc_li); $dropdown.append($sort_dec_li); $dropdown.append($dont_sort_li); } }; OncoprintTrackOptionsView.prototype.enableInteraction = function() { this.interaction_disabled = false; } OncoprintTrackOptionsView.prototype.disableInteraction = function() { this.interaction_disabled = true; } OncoprintTrackOptionsView.prototype.suppressRendering = function() { this.rendering_suppressed = true; } OncoprintTrackOptionsView.prototype.releaseRendering = function(model) { this.rendering_suppressed = false; renderAllOptions(this, model); } OncoprintTrackOptionsView.prototype.getWidth = function() { return 10 + this.img_size; } OncoprintTrackOptionsView.prototype.addTracks = function(model) { renderAllOptions(this, model); } OncoprintTrackOptionsView.prototype.moveTrack = function(model) { renderAllOptions(this, model); } OncoprintTrackOptionsView.prototype.removeTrack = function(model, track_id) { delete this.track_options_$elts[track_id]; renderAllOptions(this, model); } return OncoprintTrackOptionsView; })(); module.exports = OncoprintTrackOptionsView;
gsun83/cbioportal
portal/src/main/webapp/js/src/oncoprint/webgl/oncoprinttrackoptionsview.js
JavaScript
agpl-3.0
7,382
<%! from django.utils.translation import ugettext as _ %> <%inherit file="main.html" /> <%namespace name='static' file='static_content.html'/> <%! from django.core.urlresolvers import reverse %> <%! from django.utils.translation import ugettext as _ %> <%block name="title"><title>${_("Log into your {platform_name} Account").format(platform_name=settings.PLATFORM_NAME)}</title></%block> <%block name="js_extra"> <script type="text/javascript"> $(function() { var view_name = 'view-login'; // adding js class for styling with accessibility in mind $('body').addClass('js').addClass(view_name); // new window/tab opening $('a[rel="external"], a[class="new-vp"]') .click( function() { window.open( $(this).attr('href') ); return false; }); // form field label styling on focus $("form :input").focus(function() { $("label[for='" + this.id + "']").parent().addClass("is-focused"); }).blur(function() { $("label").parent().removeClass("is-focused"); }); }); (function() { toggleSubmitButton(true); $('#login-form').on('submit', function() { toggleSubmitButton(false); }); $('#login-form').on('ajax:error', function() { toggleSubmitButton(true); }); $('#login-form').on('ajax:success', function(event, json, xhr) { if(json.success) { var u=decodeURI(window.location.search); next=u.split("next=")[1]; if (next && !isExternal(next)) { location.href=next; } else if(json.redirect_url){ location.href=json.redirect_url; } else { location.href="${reverse('dashboard')}"; } } else if(json.hasOwnProperty('redirect')) { var u=decodeURI(window.location.search); if (!isExternal(json.redirect)) { // a paranoid check. Our server is the one providing json.redirect location.href=json.redirect+u; } // else we just remain on this page, which is fine since this particular path implies a login failure // that has been generated via packet tampering (json.redirect has been messed with). } else { toggleSubmitButton(true); $('.message.submission-error').addClass('is-shown').focus(); $('.message.submission-error .message-copy').html(json.value); } }); $("#forgot-password-link").click(function() { $("#forgot-password-modal .close-modal").focus() }) })(this); function toggleSubmitButton(enable) { var $submitButton = $('form .form-actions #submit'); if(enable) { $submitButton. removeClass('is-disabled'). removeProp('disabled'). html("${_('Log into My {platform_name} Account').format(platform_name=settings.PLATFORM_NAME)} <span class='orn-plus'>+</span> ${_('Access My Courses')}"); } else { $submitButton. addClass('is-disabled'). prop('disabled', true). html(gettext('Processing your account information &hellip;')); } } </script> </%block> <section class="introduction"> <header> <h1 class="sr">${_("Please log in to access your account and courses")}</h1> </header> </section> <section class="login container"> <section role="main" class="content"> <form role="form" id="login-form" method="post" data-remote="true" action="/login_ajax" novalidate> <!-- status messages --> <div role="alert" class="status message"> <h3 class="message-title">${_("We're Sorry, {platform_name} accounts are unavailable currently").format(platform_name=settings.PLATFORM_NAME)}</h3> </div> <div role="alert" class="status message submission-error" tabindex="-1"> <h3 class="message-title">${_("The following errors occured while logging you in:")} </h3> <ul class="message-copy"> <li>${_("Your email or password is incorrect")}</li> </ul> </div> <p class="instructions sr"> ${_('Please provide the following information to log into your {platform_name} account. Required fields are noted by <strong class="indicator">bold text and an asterisk (*)</strong>.').format(platform_name=settings.PLATFORM_NAME)} </p> <div class="group group-form group-form-requiredinformation"> <h2 class="sr">${_('Required Information')}</h2> <ol class="list-input"> <li class="field required text" id="field-email"> <label for="email">${_('E-mail')}</label> <input class="" id="email" type="email" name="email" value="" placeholder="example: username@domain.com" required aria-required="true" aria-described-by="email-tip" /> <span class="tip tip-input" id="email-tip">${_("This is the e-mail address you used to register with {platform}").format(platform=settings.PLATFORM_NAME)}</span> </li> <li class="field required password" id="field-password"> <label for="password">${_('Password')}</label> <input id="password" type="password" name="password" value="" required aria-required="true" /> <span class="tip tip-input"> <a href="#forgot-password-modal" rel="leanModal" class="pwd-reset action action-forgotpw" id="forgot-password-link" role="button" aria-haspopup="true">${_('Forgot password?')}</a> </span> </li> </ol> </div> <div class="group group-form group-form-secondary group-form-accountpreferences"> <h2 class="sr">${_('Account Preferences')}</h2> <ol class="list-input"> <li class="field required checkbox" id="field-remember"> <input id="remember-yes" type="checkbox" name="remember" value="true" /> <label for="remember-yes">${_('Remember me')}</label> </li> </ol> </div> % if course_id and enrollment_action: <input type="hidden" name="enrollment_action" value="${enrollment_action | h}" /> <input type="hidden" name="course_id" value="${course_id | h}" /> % endif <div class="form-actions"> <button name="submit" type="submit" id="submit" class="action action-primary action-update"></button> </div> </form> </section> <aside role="complementary"> <header> <h2 class="sr">${_("Helpful Information")}</h2> </header> % if settings.MITX_FEATURES.get('AUTH_USE_OPENID'): <!-- <div class="cta cta-login-options-openid"> <h3>${_("Login via OpenID")}</h3> <p>${_('You can now start learning with {platform_name} by logging in with your <a rel="external" href="http://openid.net/">OpenID account</a>.').format(platform_name=settings.PLATFORM_NAME)}</p> <a class="action action-login-openid" href="#">${_("Login via OpenID")}</a> </div> --> % endif <div class="cta cta-help"> <h3>${_("Not Enrolled?")}</h3> <p><a href="${reverse('register_user')}">${_("Sign up for {platform_name} today!").format(platform_name=settings.PLATFORM_NAME)}</a></p> ## Disable help unless the FAQ marketing link is enabled % if settings.MKTG_URL_LINK_MAP.get('FAQ'): <h3>${_("Need Help?")}</h3> <p>${_("Looking for help in logging in or with your {platform_name} account?").format(platform_name=settings.PLATFORM_NAME)} <a href="${marketing_link('FAQ')}"> ${_("View our help section for answers to commonly asked questions.")} </a></p> % endif </div> </aside> </section>
syjeon/new_edx
lms/templates/login.html
HTML
agpl-3.0
7,598
require "spec_helper" describe Admin::FormattedTimeAgoHelper do before do I18n.locale = :en end it "should return 'no action sent' when no occurrence" do since = helper.time_since_sent("trout fishing", false) since.should == "not trout fishing" end it "should return formatted time since when occurrence" do since = helper.time_since_sent("elephant hunting", 3.days.ago) since.should == "elephant hunting 3 days ago" end end
fightforthefuture/Platform
spec/helpers/admin/formatted_time_ago_spec.rb
Ruby
agpl-3.0
461
/* * SessionPackrat.cpp * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionPackrat.hpp" #include <core/Exec.hpp> #include <core/FileSerializer.hpp> #include <core/Hash.hpp> #include <core/system/FileMonitor.hpp> #include <core/RecursionGuard.hpp> #include <r/RExec.hpp> #include <r/RJson.hpp> #include <r/RRoutines.hpp> #include <r/ROptions.hpp> #include <r/session/RSessionUtils.hpp> #include <session/projects/SessionProjects.hpp> #include <session/SessionAsyncRProcess.hpp> #include <session/SessionModuleContext.hpp> #include <session/SessionPersistentState.hpp> #include "SessionPackages.hpp" #include "session-config.h" using namespace rstudio::core; #ifdef TRACE_PACKRAT_OUTPUT #define PACKRAT_TRACE(x) \ std::cerr << "(packrat) " << x << std::endl; #else #define PACKRAT_TRACE(x) #endif #define kPackratFolder "packrat/" #define kPackratLockfile "packrat.lock" #define kPackratLibPath kPackratFolder "lib" #define kPackratLockfilePath kPackratFolder kPackratLockfile #define kPackratActionRestore "restore" #define kPackratActionClean "clean" #define kPackratActionSnapshot "snapshot" #define kAutoSnapshotName "auto.snapshot" #define kAutoSnapshotDefault false #define kInvalidHashValue "--------" // aligned with a corresponding protocol version in Packrat (see // getPackageRStudioProtocol), and bumped in Packrat to indicate breaks in // compatibility with older versions of RStudio #define kPackratRStudioProtocolVersion 1 namespace rstudio { namespace session { namespace modules { namespace packrat { namespace { // Current Packrat actions and state ----------------------------------------- enum PackratActionType { PACKRAT_ACTION_NONE = 0, PACKRAT_ACTION_SNAPSHOT = 1, PACKRAT_ACTION_RESTORE = 2, PACKRAT_ACTION_CLEAN = 3, PACKRAT_ACTION_UNKNOWN = 4, PACKRAT_ACTION_MAX = PACKRAT_ACTION_UNKNOWN }; enum PackratHashType { HASH_TYPE_LOCKFILE = 0, HASH_TYPE_LIBRARY = 1 }; // Hash states are used for two purposes: // 1) To ascertain whether an object has undergone a meaningful change--for // instance, if the library state is different after an operation // 2) To track the last-resolved state of an object, as an aid for discovering // what actions are appropriate on the object // // As an example, take the lockfile hash: // HASH_STATE_COMPUTED != HASH_STATE_OBSERVED // The client's view reflects a different lockfile state. Refresh the client // view. // HASH_STATE_OBSERVED != HASH_STATE_RESOLVED // The content in the lockfile has changed since the last time a snapshot or // restore was performed. The user should perform a 'restore'. // HASH_STATE_COMPUTED == HASH_STATE_RESOLVED // The content of the lockfile is up-to-date and no action is needed. // enum PackratHashState { HASH_STATE_RESOLVED = 0, // The state last known to be consistent (stored) HASH_STATE_OBSERVED = 1, // The state last viewed by the client (stored) HASH_STATE_COMPUTED = 2 // The current state (not stored) }; enum PendingSnapshotAction { SET_PENDING_SNAPSHOT = 0, CLEAR_PENDING_SNAPSHOT = 1, EXEC_PENDING_SNAPSHOT = 2, COMPLETE_SNAPSHOT = 3 }; PackratActionType packratAction(const std::string& str) { if (str == kPackratActionSnapshot) return PACKRAT_ACTION_SNAPSHOT; else if (str == kPackratActionRestore) return PACKRAT_ACTION_RESTORE; else if (str == kPackratActionClean) return PACKRAT_ACTION_CLEAN; else return PACKRAT_ACTION_UNKNOWN; } std::string packratActionName(PackratActionType action) { switch (action) { case PACKRAT_ACTION_SNAPSHOT: return kPackratActionSnapshot; break; case PACKRAT_ACTION_RESTORE: return kPackratActionRestore; break; case PACKRAT_ACTION_CLEAN: return kPackratActionClean; break; default: return ""; } } static PackratActionType s_runningPackratAction = PACKRAT_ACTION_NONE; static bool s_autoSnapshotPending = false; static bool s_autoSnapshotRunning = false; static bool s_packageStateChanged = false; static bool s_pendingLibraryHash = false; // Forward declarations ------------------------------------------------------ void performAutoSnapshot(const std::string& targetHash, bool queue); void pendingSnapshot(PendingSnapshotAction action); bool getPendingActions(PackratActionType action, bool useCached, const std::string& libraryHash, const std::string& lockfileHash, json::Value* pActions); bool resolveStateAfterAction(PackratActionType action, PackratHashType hashType); std::string computeLockfileHash(); std::string computeLibraryHash(); // Library and lockfile hashing and comparison ------------------------------- // Returns the storage key for the given hash type and state std::string keyOfHashType(PackratHashType hashType, PackratHashState hashState) { std::string hashKey = "packrat"; hashKey.append(hashType == HASH_TYPE_LOCKFILE ? "Lockfile" : "Library"); hashKey.append(hashState == HASH_STATE_OBSERVED ? "Observed" : "Resolved"); return hashKey; } // Given the hash type and state, return the hash std::string getHash(PackratHashType hashType, PackratHashState hashState) { // For computed hashes, do the computation if (hashState == HASH_STATE_COMPUTED) { if (hashType == HASH_TYPE_LOCKFILE) return computeLockfileHash(); else return computeLibraryHash(); } else return persistentState().getStoredHash(keyOfHashType(hashType, hashState)); } void setStoredHash(PackratHashType hashType, PackratHashState hashState, const std::string& hashValue) { PACKRAT_TRACE("updating " << keyOfHashType(hashType, hashState) << " -> " << hashValue); persistentState().setStoredHash(keyOfHashType(hashType, hashState), hashValue); } std::string updateHash(PackratHashType hashType, PackratHashState hashState, const std::string& computedHash = std::string()) { // compute the hash if not already provided std::string newHash = computedHash.empty() ? getHash(hashType, HASH_STATE_COMPUTED) : computedHash; std::string oldHash = getHash(hashType, hashState); if (newHash != oldHash) setStoredHash(hashType, hashState, newHash); return newHash; } // adds content from the given file to the given file if it's a // DESCRIPTION file (used to summarize library content for hashing) void addDescContent(const FilePath& path, std::string* pDescContent) { std::string newDescContent; if (path.getFilename() == "DESCRIPTION") { Error error = readStringFromFile(path, &newDescContent); // include the path of the file; on Windows the DESCRIPTION file moves // inside the library post-installation pDescContent->append(path.getAbsolutePath()); pDescContent->append(newDescContent); } } // computes a hash of the content of all DESCRIPTION files in the Packrat // private library std::string computeLibraryHash() { // figure out what library paths are being used by Packrat std::string libraryPath; Error error = r::exec::RFunction("packrat:::libDir").call(&libraryPath); if (error) { LOG_ERROR(error); return ""; } // find DESCRIPTION files for the packages in these libraries std::string descFileContent; std::vector<FilePath> pkgPaths; error = FilePath(libraryPath).getChildren(pkgPaths); if (error) LOG_ERROR(error); for (auto& pkgPath : pkgPaths) { FilePath descPath = pkgPath.completeChildPath("DESCRIPTION"); if (descPath.exists()) addDescContent(descPath, &descFileContent); } if (descFileContent.empty()) return ""; return hash::crc32HexHash(descFileContent); } // computes the hash of the current project's lockfile std::string computeLockfileHash() { FilePath lockFilePath = projects::projectContext().directory().completePath(kPackratLockfilePath); if (!lockFilePath.exists()) return ""; std::string lockFileContent; Error error = readStringFromFile(lockFilePath, &lockFileContent); if (error) { LOG_ERROR(error); return ""; } return hash::crc32HexHash(lockFileContent); } void checkHashes( PackratHashType hashType, PackratHashState hashState, boost::function<void(const std::string&, const std::string&)> onMismatch) { // if a request to check hashes comes in while we're already checking hashes, // drop it: it's very likely that the file monitor has discovered a change // to a file we've already hashed. DROP_RECURSIVE_CALLS; std::string oldHash = getHash(hashType, hashState); std::string newHash = getHash(hashType, HASH_STATE_COMPUTED); // hashes match, no work needed if (oldHash == newHash) return; else onMismatch(oldHash, newHash); } bool hashStatesMatch(PackratHashType hashType, PackratHashState state1, PackratHashState state2) { std::string hash1 = getHash(hashType, state1); std::string hash2 = getHash(hashType, state2); if (hash1.empty() || hash2.empty()) return true; return hash1 == hash2; } bool isHashUnresolved(PackratHashType hashType) { return !hashStatesMatch(hashType, HASH_STATE_OBSERVED, HASH_STATE_RESOLVED); } // Auto-snapshot ------------------------------------------------------------- class AutoSnapshot: public async_r::AsyncRProcess { public: static boost::shared_ptr<AutoSnapshot> create( const FilePath& projectDir, const std::string& targetHash) { boost::shared_ptr<AutoSnapshot> pSnapshot(new AutoSnapshot()); std::string snapshotCmd; Error error = r::exec::RFunction( ".rs.getAutoSnapshotCmd", projectDir.getAbsolutePath()).call(&snapshotCmd); if (error) LOG_ERROR(error); // will also be reported in the console PACKRAT_TRACE("starting auto snapshot, R command: " << snapshotCmd); pSnapshot->setTargetHash(targetHash); pSnapshot->start(snapshotCmd.c_str(), projectDir, async_r::R_PROCESS_VANILLA); return pSnapshot; } std::string getTargetHash() { return targetHash_; } private: void setTargetHash(const std::string& targetHash) { targetHash_ = targetHash; } void onStderr(const std::string& output) { PACKRAT_TRACE("(auto snapshot) " << output); } void onStdout(const std::string& output) { PACKRAT_TRACE("(auto snapshot) " << output); } void onCompleted(int exitStatus) { PACKRAT_TRACE("finished auto snapshot, exit status = " << exitStatus); if (exitStatus != 0) return; pendingSnapshot(COMPLETE_SNAPSHOT); } std::string targetHash_; }; void pendingSnapshot(PendingSnapshotAction action) { switch (action) { case SET_PENDING_SNAPSHOT: if (!s_autoSnapshotPending) { PACKRAT_TRACE("queueing pending snapshot"); s_autoSnapshotPending = true; } break; case CLEAR_PENDING_SNAPSHOT: s_autoSnapshotPending = false; break; case EXEC_PENDING_SNAPSHOT: case COMPLETE_SNAPSHOT: { // prefer execution of any pending snapshots in either case if (s_autoSnapshotPending) { PACKRAT_TRACE("executing pending snapshot"); performAutoSnapshot(computeLibraryHash(), false); } // when a snapshot finishes, resolve the library state else if (action == COMPLETE_SNAPSHOT) { s_autoSnapshotRunning = false; // if there are remaining actions, re-emit the state to the client if (!resolveStateAfterAction(PACKRAT_ACTION_SNAPSHOT, HASH_TYPE_LOCKFILE)) { s_packageStateChanged = true; } } } } } // Checks Packrat options to see whether auto-snapshotting is enabled bool isAutoSnapshotEnabled() { bool enabled = kAutoSnapshotDefault; r::sexp::Protect rProtect; SEXP optionsSEXP; Error error = modules::packrat::getPackratOptions(&optionsSEXP, &rProtect); if (!error) { error = r::sexp::getNamedListElement(optionsSEXP, kAutoSnapshotName, &enabled, kAutoSnapshotDefault); } return enabled; } // Performs an automatic snapshot of the Packrat library, either immediately // or later (if queue == false). In either case, does not perform a snapshot // if one is already running for the requested state, or if there are // unresolved changes in the lockfile. void performAutoSnapshot(const std::string& newHash, bool queue) { static boost::shared_ptr<AutoSnapshot> pAutoSnapshot; if (pAutoSnapshot && pAutoSnapshot->isRunning()) { // is the requested snapshot for the same state we're already // snapshotting? if it is, ignore the request if (pAutoSnapshot->getTargetHash() == newHash) { PACKRAT_TRACE("snapshot already running (" << newHash << ")"); return; } else { pendingSnapshot(SET_PENDING_SNAPSHOT); return; } } // make sure we have no unresolved lockfile changes if (isHashUnresolved(HASH_TYPE_LOCKFILE)) { PACKRAT_TRACE("not performing automatic snapshot; resolve pending (" << getHash(HASH_TYPE_LOCKFILE, HASH_STATE_RESOLVED) << ", " << getHash(HASH_TYPE_LOCKFILE, HASH_STATE_COMPUTED) << ")"); return; } if (queue && isAutoSnapshotEnabled()) { pendingSnapshot(SET_PENDING_SNAPSHOT); } else { if (!isAutoSnapshotEnabled()) { PACKRAT_TRACE("not performing automatic snapshot; automatic " "snapshots currently disabled in options"); return; } // start a new auto-snapshot pendingSnapshot(CLEAR_PENDING_SNAPSHOT); s_autoSnapshotRunning = true; pAutoSnapshot = AutoSnapshot::create( projects::projectContext().directory(), newHash); } } // Library and lockfile monitoring ------------------------------------------- // indicates whether there are any actions that would be performed if the given // action were executed; if there are actions, they are returned in pActions. bool getPendingActions(PackratActionType action, bool useCached, const std::string& libraryHash, const std::string& lockfileHash, json::Value* pActions) { // checking for actions can be expensive--if this call is for the same // action with the same library and lockfile states for which we previously // queried for that action, serve cached state static std::string cachedLibraryHash[PACKRAT_ACTION_MAX]; static std::string cachedLockfileHash[PACKRAT_ACTION_MAX]; static bool cachedResult[PACKRAT_ACTION_MAX]; static json::Value cachedActions[PACKRAT_ACTION_MAX]; if (libraryHash == cachedLibraryHash[action] && lockfileHash == cachedLockfileHash[action] && useCached) { PACKRAT_TRACE("using cached action list for action '" << packratActionName(action) << "' (" << libraryHash << ", " << lockfileHash << ")"); if (pActions && !cachedActions[action].isNull()) *pActions = cachedActions[action]; return cachedResult[action]; } PACKRAT_TRACE("caching action list for action '" << packratActionName(action) << "' (" << libraryHash << ", " << lockfileHash << ")"); // record state for later service from cache cachedLibraryHash[action] = libraryHash; cachedLockfileHash[action] = lockfileHash; cachedActions[action] = json::Value(); // get the list of actions from Packrat SEXP actions; r::sexp::Protect protect; Error error = r::exec::RFunction(".rs.pendingActions", packratActionName(action), projects::projectContext().directory().getAbsolutePath()) .call(&actions, &protect); // if an error occurs, presume that there are pending actions (i.e. don't // resolve the state) if (error) { LOG_ERROR(error); return (cachedResult[action] = true); } // if an empty list comes back, we can savely resolve the state if (r::sexp::length(actions) == 0) return (cachedResult[action] = false); // convert the action list to JSON if needed error = r::json::jsonValueFromObject(actions, &(cachedActions[action])); if (pActions) *pActions = cachedActions[action]; return (cachedResult[action] = !error); } void onLockfileUpdate(const std::string& oldHash, const std::string& newHash) { // if the lockfile changed, refresh to show the new Packrat state s_packageStateChanged = true; } void onLibraryUpdate(const std::string& oldHash, const std::string& newHash) { // perform an auto-snapshot if we don't have a pending restore if (!isHashUnresolved(HASH_TYPE_LOCKFILE)) { performAutoSnapshot(newHash, true); } else { PACKRAT_TRACE("lockfile observed hash " << getHash(HASH_TYPE_LOCKFILE, HASH_STATE_OBSERVED) << " doesn't match resolved hash " << getHash(HASH_TYPE_LOCKFILE, HASH_STATE_RESOLVED) << ", skipping auto snapshot"); } // send the new state to the client if Packrat isn't busy if (s_runningPackratAction == PACKRAT_ACTION_NONE) s_packageStateChanged = true; } void onFileChanged(FilePath sourceFilePath) { // ignore file changes while Packrat is running if (s_runningPackratAction != PACKRAT_ACTION_NONE) return; // we only care about mutations to files in the Packrat library directory // (and packrat.lock) FilePath libraryPath = projects::projectContext().directory().completePath(kPackratLibPath); if (sourceFilePath.getFilename() == kPackratLockfile) { PACKRAT_TRACE("detected change to lockfile " << sourceFilePath); checkHashes(HASH_TYPE_LOCKFILE, HASH_STATE_OBSERVED, onLockfileUpdate); } else if (sourceFilePath.isWithin(libraryPath) && (sourceFilePath.isDirectory() || sourceFilePath.getFilename() == "DESCRIPTION")) { // ignore changes in the RStudio-managed manipulate and rstudio // directories and the files within them if (sourceFilePath.getFilename() == "manipulate" || sourceFilePath.getFilename() == "rstudio" || sourceFilePath.getParent().getFilename() == "manipulate" || sourceFilePath.getParent().getFilename() == "rstudio") { return; } PACKRAT_TRACE("detected change to library file " << sourceFilePath); s_pendingLibraryHash = true; } } void onFilesChanged(const std::vector<core::system::FileChangeEvent>& changes) { for (const core::system::FileChangeEvent& fileChange : changes) { FilePath changedFilePath(fileChange.fileInfo().absolutePath()); onFileChanged(changedFilePath); } } void onConsolePrompt(const std::string& prompt) { // Execute pending auto-snapshots if any exist. We don't execute these // immediately on detecting a change since a bulk change may be in-flight // (e.g. installing a package and several upon which it depends) pendingSnapshot(EXEC_PENDING_SNAPSHOT); } // RPC ----------------------------------------------------------------------- Error installPackrat(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { Error error = module_context::installEmbeddedPackage("packrat"); if (error) { std::string desc = error.getProperty("description"); if (desc.empty()) desc = error.getSummary(); module_context::consoleWriteError(desc + "\n"); LOG_ERROR(error); } pResponse->setResult(!error); return Success(); } Error getPackratPrerequisites(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { json::Object prereqJson; using namespace module_context; prereqJson["build_tools_available"] = canBuildCpp(); prereqJson["package_available"] = isRequiredPackratInstalled(); pResponse->setResult(prereqJson); return Success(); } Error getPackratContext(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { pResponse->setResult(module_context::packratContextAsJson()); return Success(); } Error packratBootstrap(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // read params std::string dir; bool enter = false; Error error = json::readParams(request.params, &dir, &enter); if (error) return error; // convert to file path then to system encoding FilePath dirPath = module_context::resolveAliasedPath(dir); dir = string_utils::utf8ToSystem(dirPath.getAbsolutePath()); // bootstrap r::exec::RFunction bootstrap("packrat:::init"); bootstrap.addParam("project", dir); bootstrap.addParam("enter", enter); bootstrap.addParam("restart", false); error = bootstrap.call(); if (error) LOG_ERROR(error); // will also be reported in the console // return status return Success(); } Error initPackratMonitoring() { FilePath lockfilePath = projects::projectContext().directory().completePath(kPackratLockfilePath); // if there's no lockfile, presume that this isn't a Packrat project if (!lockfilePath.exists()) return Success(); // listen for changes to the project files PACKRAT_TRACE("found " << lockfilePath.getAbsolutePath() << ", init monitoring"); session::projects::FileMonitorCallbacks cb; cb.onFilesChanged = onFilesChanged; projects::projectContext().subscribeToFileMonitor("Packrat", cb); using namespace module_context; events().onSourceEditorFileSaved.connect(onFileChanged); events().onConsolePrompt.connect(onConsolePrompt); return Success(); } // runs after an (auto) snapshot or restore; returns whether the state was // resolved successfully bool resolveStateAfterAction(PackratActionType action, PackratHashType hashType) { // compute the new library and lockfile states std::string newLibraryHash = getHash(HASH_TYPE_LIBRARY, HASH_STATE_COMPUTED); std::string newLockfileHash = getHash(HASH_TYPE_LOCKFILE, HASH_STATE_COMPUTED); // mark the library resolved if there are no pending snapshot actions bool hasPendingSnapshotActions = getPendingActions(PACKRAT_ACTION_SNAPSHOT, true, newLibraryHash, newLockfileHash, nullptr); if (!hasPendingSnapshotActions) updateHash(HASH_TYPE_LIBRARY, HASH_STATE_RESOLVED, newLibraryHash); // mark the lockfile resolved if there are no pending restore actions bool hasPendingRestoreActions = getPendingActions(PACKRAT_ACTION_RESTORE, true, newLibraryHash, newLockfileHash, nullptr); if (hasPendingRestoreActions) { // if we just finished a snapshot and there are pending restore actions, // dirty the lockfile so they'll get applied if (action == PACKRAT_ACTION_SNAPSHOT && !hasPendingSnapshotActions) setStoredHash(HASH_TYPE_LOCKFILE, HASH_STATE_RESOLVED, kInvalidHashValue); } else updateHash(HASH_TYPE_LOCKFILE, HASH_STATE_RESOLVED, newLockfileHash); // if the action changed the underlying store, send the new state to the // client bool hashChangedState = !hashStatesMatch(hashType, HASH_STATE_OBSERVED, HASH_STATE_COMPUTED); if (hashChangedState) s_packageStateChanged = true; return hashChangedState || !(hasPendingSnapshotActions || hasPendingRestoreActions); } // Notification that a packrat action has either started or // stopped (indicated by the "running" flag). Possible values for // action are: "snapshot", "restore", and "clean" void onPackratAction(const std::string& project, const std::string& action, bool running) { // if this doesn't apply to the current project then skip it if (!core::system::realPathsEqual( projects::projectContext().directory(), FilePath(project))) { return; } if (running && (s_runningPackratAction != PACKRAT_ACTION_NONE)) { PACKRAT_TRACE("warning: '" << action << "' executed while action " << s_runningPackratAction << " was already running"); } PACKRAT_TRACE("packrat action '" << action << "' " << (running ? "started" : "finished")); // action started, cache it and return if (running) { s_runningPackratAction = packratAction(action); return; } PackratActionType completedAction = s_runningPackratAction; s_runningPackratAction = PACKRAT_ACTION_NONE; // action ended, update hashes accordingly switch (completedAction) { case PACKRAT_ACTION_RESTORE: resolveStateAfterAction(PACKRAT_ACTION_RESTORE, HASH_TYPE_LIBRARY); break; case PACKRAT_ACTION_SNAPSHOT: resolveStateAfterAction(PACKRAT_ACTION_SNAPSHOT, HASH_TYPE_LOCKFILE); break; default: break; } } SEXP rs_onPackratAction(SEXP projectSEXP, SEXP actionSEXP, SEXP runningSEXP) { std::string project = r::sexp::safeAsString(projectSEXP); std::string action = r::sexp::safeAsString(actionSEXP); bool running = r::sexp::asLogical(runningSEXP); onPackratAction(project, action, running); return R_NilValue; } void detectReposChanges() { static SEXP s_lastReposSEXP = R_UnboundValue; SEXP reposSEXP = r::options::getOption("repos"); if (s_lastReposSEXP == R_UnboundValue) { s_lastReposSEXP = reposSEXP; } else if (reposSEXP != s_lastReposSEXP) { s_lastReposSEXP = reposSEXP; performAutoSnapshot(getHash(HASH_TYPE_LIBRARY, HASH_STATE_COMPUTED), false); } } void onDetectChanges(module_context::ChangeSource source) { if (source == module_context::ChangeSourceREPL) detectReposChanges(); // Update hashes. if (s_pendingLibraryHash) { s_pendingLibraryHash = false; checkHashes(HASH_TYPE_LIBRARY, HASH_STATE_OBSERVED, onLibraryUpdate); } // If the package state has changed, report those changes to the client. if (s_packageStateChanged) { s_packageStateChanged = false; packages::enquePackageStateChanged(); } } void activatePackagesIfPendingActions() { // activate the packages pane if the library or lockfile states are // unresolved (i.e. there is a pending snapshot or restore) if (!(hashStatesMatch(HASH_TYPE_LOCKFILE, HASH_STATE_COMPUTED, HASH_STATE_RESOLVED) && hashStatesMatch(HASH_TYPE_LIBRARY, HASH_STATE_COMPUTED, HASH_STATE_RESOLVED))) { module_context::activatePane("packages"); } } void afterSessionInitHook(bool newSession) { // additional stuff if we are in packrat mode if (module_context::packratContext().modeOn) { Error error = r::exec::RFunction(".rs.installPackratActionHook").call(); if (error) LOG_ERROR(error); error = initPackratMonitoring(); if (error) LOG_ERROR(error); module_context::events().onDetectChanges.connect(onDetectChanges); // check whether there are pending actions and if there are then // ensure that the packages pane is activated. we do this on a // delayed basis to allow all of the other IDE initialization // RPC calls (list files, list environment, etc.) to occur before // we begin the (more latent) listing of packages + actions if (newSession) { activatePackagesIfPendingActions(); } } } } // anonymous namespace Error getPackratOptions(SEXP* pOptionsSEXP, r::sexp::Protect* pRProtect) { FilePath projectDir = projects::projectContext().directory(); r::exec::RFunction getOpts("packrat:::get_opts"); getOpts.addParam("simplify", false); getOpts.addParam("project", module_context::createAliasedPath(projectDir)); return getOpts.call(pOptionsSEXP, pRProtect); } json::Object contextAsJson(const module_context::PackratContext& context) { json::Object contextJson; contextJson["available"] = context.available; contextJson["applicable"] = context.applicable; contextJson["packified"] = context.packified; contextJson["mode_on"] = context.modeOn; return contextJson; } json::Object contextAsJson() { module_context::PackratContext context = module_context::packratContext(); return contextAsJson(context); } Error getPackratActions(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { json::Value restoreActions; json::Value snapshotActions; json::Object json; std::string oldLibraryHash = getHash(HASH_TYPE_LIBRARY, HASH_STATE_OBSERVED); // compute new hashes and mark them observed std::string newLibraryHash = updateHash(HASH_TYPE_LIBRARY, HASH_STATE_OBSERVED); std::string newLockfileHash = updateHash(HASH_TYPE_LOCKFILE, HASH_STATE_OBSERVED); // take an auto-snapshot if the library hashes don't match: it's necessary // to do this here in case we've observed the new hash before the file // monitor had a chance to see it if (oldLibraryHash != newLibraryHash) performAutoSnapshot(newLibraryHash, false); // if we're waiting for an auto snapshot or Packrat is doing work, don't // bug the user with a list of actions until that work is finished. if (!s_autoSnapshotPending && !s_autoSnapshotRunning && s_runningPackratAction == PACKRAT_ACTION_NONE) { // check for pending restore and snapshot actions bool hasPendingSnapshotActions = getPendingActions(PACKRAT_ACTION_SNAPSHOT, false, newLibraryHash, newLockfileHash, &snapshotActions); bool hasPendingRestoreActions = getPendingActions(PACKRAT_ACTION_RESTORE, false, newLibraryHash, newLockfileHash, &restoreActions); // if the state could be interpreted as either a pending restore or a // pending snapsot, try to guess which is appropriate if (hasPendingRestoreActions && hasPendingSnapshotActions) { bool libraryDirty = newLibraryHash != getHash(HASH_TYPE_LIBRARY, HASH_STATE_RESOLVED); bool lockfileDirty = newLockfileHash != getHash(HASH_TYPE_LOCKFILE, HASH_STATE_RESOLVED); // hide the list of pending restore actions if we think a snapshot is // appropriate, and vice versa if (libraryDirty && !lockfileDirty) restoreActions = json::Value(); if (!libraryDirty && lockfileDirty) snapshotActions = json::Value(); } } json["restore_actions"] = restoreActions; json["snapshot_actions"] = snapshotActions; pResponse->setResult(json); return Success(); } Error initialize() { // register deferred init (since we need to call into the packrat package // we need to wait until all other modules initialize and all R routines // are initialized -- otherwise the package load hook attempts to call // rs_packageLoaded and can't find it // // we want this to occur _after_ packrat has done its own initialization, // so we ensure that the package hooks are run before this module_context::events().afterSessionInitHook.connect(afterSessionInitHook); // register packrat action hook RS_REGISTER_CALL_METHOD(rs_onPackratAction); using boost::bind; using namespace module_context; ExecBlock initBlock; initBlock.addFunctions() (bind(registerRpcMethod, "install_packrat", installPackrat)) (bind(registerRpcMethod, "get_packrat_prerequisites", getPackratPrerequisites)) (bind(registerRpcMethod, "get_packrat_context", getPackratContext)) (bind(registerRpcMethod, "packrat_bootstrap", packratBootstrap)) (bind(registerRpcMethod, "get_packrat_actions", getPackratActions)) (bind(sourceModuleRFile, "SessionPackrat.R")); return initBlock.execute(); } } // namespace packrat } // namespace modules namespace module_context { bool isRequiredPackratInstalled() { return getPackageCompatStatus("packrat", "0.4.6", kPackratRStudioProtocolVersion) == COMPAT_OK; } PackratContext packratContext() { PackratContext context; // packrat is available in R >= 3.0 context.available = r::session::utils::isR3(); context.applicable = context.available && projects::projectContext().hasProject(); // if it's applicable and installed then check packrat status if (context.applicable && isRequiredPackratInstalled()) { FilePath projectDir = projects::projectContext().directory(); std::string projectPath = string_utils::utf8ToSystem(projectDir.getAbsolutePath()); // check and see if the project has been packified Error error = r::exec::RFunction(".rs.isPackified") .addParam(projectPath) .call(&context.packified); if (error) LOG_ERROR(error); if (context.packified) { Error error = r::exec::RFunction( ".rs.isPackratModeOn", projectPath).call(&context.modeOn); if (error) LOG_ERROR(error); // cache results in project directory to make packrat status information available on session start persistentState().settings().set("packratEnabled", context.modeOn); } } return context; } json::Object packratContextAsJson() { return modules::packrat::contextAsJson(); } namespace { template <typename T> void copyOption(SEXP optionsSEXP, const std::string& listName, json::Object* pOptionsJson, const std::string& jsonName, T defaultValue) { T value = defaultValue; Error error = r::sexp::getNamedListElement(optionsSEXP, listName, &value, defaultValue); if (error) { error.addProperty("option", listName); LOG_ERROR(error); } (*pOptionsJson)[jsonName] = value; } void copyOptionArrayString(SEXP optionsSEXP, const std::string& listName, json::Object* pOptionsJson, const std::string& jsonName, std::vector<std::string> defaultValue) { std::vector<std::string> value = defaultValue; Error error = r::sexp::getNamedListElement(optionsSEXP, listName, &value, defaultValue); if (error) { error.addProperty("option", listName); LOG_ERROR(error); } (*pOptionsJson)[jsonName] = json::toJsonArray(value); } json::Object defaultPackratOptions() { json::Object optionsJson; optionsJson["use_packrat"] = false; optionsJson["auto_snapshot"] = kAutoSnapshotDefault; optionsJson["vcs_ignore_lib"] = true; optionsJson["vcs_ignore_src"] = false; optionsJson["use_cache"] = false; optionsJson["external_packages"] = json::toJsonArray(std::vector<std::string>()); optionsJson["local_repos"] = json::toJsonArray(std::vector<std::string>()); return optionsJson; } } // anonymous namespace json::Object packratOptionsAsJson() { PackratContext context = packratContext(); if (context.packified) { // create options to return json::Object optionsJson; optionsJson["use_packrat"] = true; r::sexp::Protect rProtect; SEXP optionsSEXP; Error error = modules::packrat::getPackratOptions(&optionsSEXP, &rProtect); if (error) { LOG_ERROR(error); return defaultPackratOptions(); } // copy the options into json copyOption(optionsSEXP, kAutoSnapshotName, &optionsJson, "auto_snapshot", true); copyOption(optionsSEXP, "vcs.ignore.lib", &optionsJson, "vcs_ignore_lib", true); copyOption(optionsSEXP, "vcs.ignore.src", &optionsJson, "vcs_ignore_src", false); copyOption(optionsSEXP, "use.cache", &optionsJson, "use_cache", false); copyOptionArrayString(optionsSEXP, "external.packages", &optionsJson, "external_packages", std::vector<std::string>()); copyOptionArrayString(optionsSEXP, "local.repos", &optionsJson, "local_repos", std::vector<std::string>()); return optionsJson; } else { return defaultPackratOptions(); } } } // namespace module_context } // namespace session } // namespace rstudio
JanMarvin/rstudio
src/cpp/session/modules/SessionPackrat.cpp
C++
agpl-3.0
38,183
# # Copyright (C) 2011 Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # require 'net/http' require 'uri' class WimbaConference < WebConference external_url :archive, :name => lambda{ t('external_urls.archive', "Archive") }, :link_text => lambda{ t('external_urls.archive_link', "View archive(s)") }, :restricted_to => lambda{ |conf| conf.active? || conf.finished? } def archive_external_url(user, url_id) urls = [] if (res = send_request('listClass', {'filter00' => 'archive_of', 'filter00value' => wimba_id, 'attribute' => 'longname'})) res.sub(/\A100 OK\n/, '').split(/\n=END RECORD\n?/).each do |match| data = match.split(/\n/).inject({}){ |hash, line| key, hash[key.to_sym] = line.split(/=/, 2); hash} unless data[:longname] && data[:class_id] logger.error "wimba error reading archive list" break end if date_info = data[:longname].match(Regexp.new(" - (\\d{2}/\\d{2}/\\d{4} \\d{2}:\\d{2})\\z")) # convert from wimba's local time to the user's local time tz = ActiveSupport::TimeZone[config[:timezone] || config[:plugin].default_settings[:timezone]] new_date = nil Time.use_zone(tz) do new_date = datetime_string(DateTime.strptime(date_info[1], '%m/%d/%Y %H:%M')) end data[:longname].sub!(date_info[1], new_date) end urls << {:id => data[:class_id], :name => data[:longname]} unless url_id && data[:class_id] != url_id end urls.first[:url] = join_url(user, urls.first[:id]) if urls.size == 1 && touch_user(user) end urls end def server config[:domain] end def craft_api_url(action, opts={}) url = "http://#{server}/admin/api/api.pl" query_string = "function=#{action.to_s}" opts.each do |key, val| query_string += "&#{CGI::escape(key)}=#{CGI::escape(val.to_s)}" end url + "?" + query_string end def send_request(action, opts={}) headers = {} if action.to_s == 'Init' url = craft_api_url('NoOp', { 'AuthType' => 'AuthCookieHandler', 'AuthName' => 'Horizon', 'credential_0' => config[:user], 'credential_1' => config[:password_dec] }) else init_session or return nil url = craft_api_url(action, opts) headers['Cookie'] = @auth_cookie end uri = URI.parse(url) res = nil # TODO: rework this so that we reuse the same tcp conn (we may call # send_request multiple times in the course of one browser request). Net::HTTP.start(uri.host, uri.port) do |http| http.read_timeout = 10 5.times do # follow redirects, but not forever logger.debug "wimba api call: #{uri.path}?#{uri.query}" res = http.request_get("#{uri.path}?#{uri.query}", headers) if res['Set-Cookie'] && res['Set-Cookie'] =~ /AuthCookieHandler_Horizon=.*;/ @auth_cookie = headers['Cookie'] = res['Set-Cookie'].sub(/.*(AuthCookieHandler_Horizon=.*?);.*/, '\\1') end if res.is_a?(Net::HTTPRedirection) url = res['location'] uri = URI.parse(url) else break end end end case res when Net::HTTPSuccess api_status = res.body.to_s.split("\n").first.split(" ", 2) if api_status[0] == "100" logger.debug "wimba api success: #{res.body}" return res.body end # any other status indicates an error logger.error "wimba api error #{api_status[1]} (#{api_status[0]})" else logger.error "wimba http error #{res}" end nil rescue Timeout::Error logger.error "wimba timeout error" nil rescue logger.error "wimba unhandled exception #{$!}" nil end def touch_user(user) send_request('modifyUser', { 'target' => wimba_id(user.uuid), 'password_type' => 'A', 'first_name' => user.first_name, 'last_name' => user.last_name}) || send_request('createUser', { 'target' => wimba_id(user.uuid), 'password_type' => 'A', 'first_name' => user.first_name, 'last_name' => user.last_name}) end def add_user_to_conference(user, role=:participant) touch_user(user) && send_request('createRole', { 'target' => wimba_id, 'user_id' => wimba_id(user.uuid), 'role_id' => case role when :presenter; 'Instructor' when :admin; 'ClassAdmin' else 'Student' end }) end def remove_user_from_conference(user) send_request('deleteRole', { 'target' => wimba_id, 'user_id' => wimba_id(user.uuid) }) end def join_url(user, room_id=wimba_id) (token = get_auth_token(user)) && "http://#{server}/launcher.cgi.pl?hzA=#{CGI::escape(token)}&room=#{CGI::escape(room_id)}" end def settings_url(user, room_id=wimba_id) (token = get_auth_token(user)) && "http://#{server}/admin/class/create_manage_frameset.html.epl?hzA=#{CGI::escape(token)}&class_id=#{CGI::escape(room_id)}" end def get_auth_token(user) (res = send_request('getAuthToken', { 'target' => wimba_id(user.uuid), 'nickname' => user.name.gsub(/[^a-zA-Z0-9]/, '')})) && (token = res.split("\n").detect{|s| s.match(/^authToken/) }) && token.split(/=/, 2).last.chomp end def admin_join_url(user, return_to="http://www.jiaoxuebang.com") add_user_to_conference(user, :presenter) && join_url(user) end def admin_settings_url(user, return_to="http://www.jiaoxuebang.com") initiate_conference and touch or return nil add_user_to_conference(user, :admin) && settings_url(user) end def participant_join_url(user, return_to="http://www.jiaoxuebang.com") add_user_to_conference(user) && join_url(user) end def initiate_conference return conference_key if conference_key self.conference_key = uuid send_request('createClass', { 'target' => wimba_id, 'longname' => title[0,50], 'preview' => '0', # we want the room open by default 'auto_open_new_archives' => '1' }) or return nil save conference_key end def init_session if !@auth_cookie send_request('Init') or return false end true end def conference_status active = nil if res = send_request('statusClass', {'target' => wimba_id}) res.split(/\r?\n/).each do |str| key, value = str.strip.split(/=/, 2) if key == 'num_users' return :closed unless value.to_i > 0 active = true end if key == 'roomlock' return :closed if value.to_i == 1 active = true end end end active ? :active : :closed end def wimba_id(id = uuid) # wimba ids are limited to 34 chars. assuming we are using uuids, we can put an "IN" prefix, # which makes distinguishing these users easier. "IN" + id.delete("-")[0,32] end end
rup/Tarrax
app/models/wimba_conference.rb
Ruby
agpl-3.0
7,570
<?php namespace Action; use Core\Listener; /** * Base class for automatic actions * * @package action * @author Frederic Guillot */ abstract class Base implements Listener { /** * Project id * * @access private * @var integer */ private $project_id = 0; /** * User parameters * * @access private * @var array */ private $params = array(); /** * Execute the action * * @abstract * @access public * @param array $data Event data dictionary * @return bool True if the action was executed or false when not executed */ abstract public function doAction(array $data); /** * Get the required parameter for the action (defined by the user) * * @abstract * @access public * @return array */ abstract public function getActionRequiredParameters(); /** * Get the required parameter for the event (check if for the event data) * * @abstract * @access public * @return array */ abstract public function getEventRequiredParameters(); /** * Constructor * * @access public * @param integer $project_id Project id */ public function __construct($project_id) { $this->project_id = $project_id; } /** * Set an user defined parameter * * @access public * @param string $name Parameter name * @param mixed $value Value */ public function setParam($name, $value) { $this->params[$name] = $value; } /** * Get an user defined parameter * * @access public * @param string $name Parameter name * @param mixed $default_value Default value * @return mixed */ public function getParam($name, $default_value = null) { return isset($this->params[$name]) ? $this->params[$name] : $default_value; } /** * Check if an action is executable (right project and required parameters) * * @access public * @param array $data Event data dictionary * @return bool True if the action is executable */ public function isExecutable(array $data) { if (isset($data['project_id']) && $data['project_id'] == $this->project_id && $this->hasRequiredParameters($data)) { return true; } return false; } /** * Check if the event data has required parameters to execute the action * * @access public * @param array $data Event data dictionary * @return bool True if all keys are there */ public function hasRequiredParameters(array $data) { foreach ($this->getEventRequiredParameters() as $parameter) { if (! isset($data[$parameter])) return false; } return true; } /** * Execute the action * * @access public * @param array $data Event data dictionary * @return bool True if the action was executed or false when not executed */ public function execute(array $data) { if ($this->isExecutable($data)) { return $this->doAction($data); } return false; } }
jesusaplsoft/kanboard
app/Action/Base.php
PHP
agpl-3.0
3,310
<div class="page-header"> <h2><?= t('Edit a task') ?></h2> </div> <section id="task-section"> <form method="post" action="<?= $this->url->href('task', 'update', array('task_id' => $task['id'], 'project_id' => $task['project_id'], 'ajax' => $ajax)) ?>" autocomplete="off"> <?= $this->form->csrf() ?> <div class="form-column"> <?= $this->form->label(t('Title'), 'title') ?> <?= $this->form->text('title', $values, $errors, array('autofocus', 'required', 'maxlength="200"', 'tabindex="1"')) ?><br/> <?= $this->form->label(t('Description'), 'description') ?> <div class="form-tabs"> <div class="write-area"> <?= $this->form->textarea('description', $values, $errors, array('placeholder="'.t('Leave a description').'"', 'tabindex="2"')) ?> </div> <div class="preview-area"> <div class="markdown"></div> </div> <ul class="form-tabs-nav"> <li class="form-tab form-tab-selected"> <i class="fa fa-pencil-square-o fa-fw"></i><a id="markdown-write" href="#"><?= t('Write') ?></a> </li> <li class="form-tab"> <a id="markdown-preview" href="#"><i class="fa fa-eye fa-fw"></i><?= t('Preview') ?></a> </li> </ul> </div> <div class="form-help"><a href="http://kanboard.net/documentation/syntax-guide" target="_blank" rel="noreferrer"><?= t('Write your text in Markdown') ?></a></div> </div> <div class="form-column"> <?= $this->form->hidden('id', $values) ?> <?= $this->form->hidden('project_id', $values) ?> <?= $this->form->label(t('Assignee'), 'owner_id') ?> <?= $this->form->select('owner_id', $users_list, $values, $errors, array('tabindex="3"')) ?><br/> <?= $this->form->label(t('Category'), 'category_id') ?> <?= $this->form->select('category_id', $categories_list, $values, $errors, array('tabindex="4"')) ?><br/> <?= $this->form->label(t('Color'), 'color_id') ?> <?= $this->form->select('color_id', $colors_list, $values, $errors, array('tabindex="5"')) ?><br/> <?= $this->form->label(t('Complexity'), 'score') ?> <?= $this->form->number('score', $values, $errors, array('tabindex="6"')) ?><br/> <?= $this->form->label(t('Due Date'), 'date_due') ?> <?= $this->form->text('date_due', $values, $errors, array('placeholder="'.$this->text->in($date_format, $date_formats).'"', 'tabindex="7"'), 'form-date') ?><br/> <div class="form-help"><?= t('Others formats accepted: %s and %s', date('Y-m-d'), date('Y_m_d')) ?></div> </div> <div class="form-actions"> <input type="submit" value="<?= t('Save') ?>" class="btn btn-blue" tabindex="10"> <?= t('or') ?> <?php if ($ajax): ?> <?= $this->url->link(t('cancel'), 'board', 'show', array('project_id' => $task['project_id']), false, 'close-popover') ?> <?php else: ?> <?= $this->url->link(t('cancel'), 'task', 'show', array('task_id' => $task['id'], 'project_id' => $task['project_id'])) ?> <?php endif ?> </div> </form> </section>
crwilliams/kanboard
app/Template/task/edit.php
PHP
agpl-3.0
3,233
package Locale::Codes::LangExt; # Copyright (c) 2011-2012 Sullivan Beck # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. use strict; require 5.006; use warnings; require Exporter; use Carp; use Locale::Codes; use Locale::Codes::Constants; use Locale::Codes::LangExt_Codes; use Locale::Codes::LangExt_Retired; #======================================================================= # Public Global Variables #======================================================================= our($VERSION,@ISA,@EXPORT,@EXPORT_OK); $VERSION='3.24'; @ISA = qw(Exporter); @EXPORT = qw(code2langext langext2code all_langext_codes all_langext_names langext_code2code LOCALE_LANGEXT_ALPHA ); sub code2langext { return Locale::Codes::_code2name('langext',@_); } sub langext2code { return Locale::Codes::_name2code('langext',@_); } sub langext_code2code { return Locale::Codes::_code2code('langext',@_); } sub all_langext_codes { return Locale::Codes::_all_codes('langext',@_); } sub all_langext_names { return Locale::Codes::_all_names('langext',@_); } sub rename_langext { return Locale::Codes::_rename('langext',@_); } sub add_langext { return Locale::Codes::_add_code('langext',@_); } sub delete_langext { return Locale::Codes::_delete_code('langext',@_); } sub add_langext_alias { return Locale::Codes::_add_alias('langext',@_); } sub delete_langext_alias { return Locale::Codes::_delete_alias('langext',@_); } sub rename_langext_code { return Locale::Codes::_rename_code('langext',@_); } sub add_langext_code_alias { return Locale::Codes::_add_code_alias('langext',@_); } sub delete_langext_code_alias { return Locale::Codes::_delete_code_alias('langext',@_); } 1; # Local Variables: # mode: cperl # indent-tabs-mode: nil # cperl-indent-level: 3 # cperl-continued-statement-offset: 2 # cperl-continued-brace-offset: 0 # cperl-brace-offset: 0 # cperl-brace-imaginary-offset: 0 # cperl-label-offset: -2 # End:
rahulvador/CoreHD
Kernel/cpan-lib/Locale/Codes/LangExt.pm
Perl
agpl-3.0
2,127
(() => { /** * Use iframe.ly for instagram */ const instagramService = (iframelyService, $q) => { return { name: 'Instagram', patterns: ['(?:(?:http|https):\/\/)?(?:www.)?(?:instagr(?:\.am|am\.com))\/p\/.+'], // eslint-disable-line embed: (url, max_width) => { // eslint-disable-line const deferred = $q.defer(); iframelyService.embed(url, true).then( (response) => { deferred.resolve(response); }, (error) => { deferred.reject(error.error_message || error.data.error_message); } ); return deferred.promise; }, }; }; angular.module('angular-embed.handlers') .service('embedInstagramHandler', ['iframelyService', '$q', instagramService]); })();
liveblog/liveblog
client/app/scripts/liveblog-edit/embed/handlers/instagram.ts
TypeScript
agpl-3.0
935
""" Tests for wiki views. """ from django.conf import settings from django.test.client import RequestFactory from lms.djangoapps.courseware.tabs import get_course_tab_list from common.djangoapps.student.tests.factories import AdminFactory, UserFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory class WikiTabTestCase(ModuleStoreTestCase): """Test cases for Wiki Tab.""" def setUp(self): super().setUp() self.course = CourseFactory.create() self.instructor = AdminFactory.create() self.user = UserFactory() def get_wiki_tab(self, user, course): """Returns true if the "Wiki" tab is shown.""" request = RequestFactory().request() all_tabs = get_course_tab_list(user, course) wiki_tabs = [tab for tab in all_tabs if tab.name == 'Wiki'] return wiki_tabs[0] if len(wiki_tabs) == 1 else None def test_wiki_enabled_and_public(self): """ Test wiki tab when Enabled setting is True and the wiki is open to the public. """ settings.WIKI_ENABLED = True self.course.allow_public_wiki_access = True assert self.get_wiki_tab(self.user, self.course) is not None def test_wiki_enabled_and_not_public(self): """ Test wiki when it is enabled but not open to the public """ settings.WIKI_ENABLED = True self.course.allow_public_wiki_access = False assert self.get_wiki_tab(self.user, self.course) is None assert self.get_wiki_tab(self.instructor, self.course) is not None def test_wiki_enabled_false(self): """Test wiki tab when Enabled setting is False""" settings.WIKI_ENABLED = False assert self.get_wiki_tab(self.user, self.course) is None assert self.get_wiki_tab(self.instructor, self.course) is None def test_wiki_visibility(self): """Test toggling of visibility of wiki tab""" settings.WIKI_ENABLED = True self.course.allow_public_wiki_access = True wiki_tab = self.get_wiki_tab(self.user, self.course) assert wiki_tab is not None assert wiki_tab.is_hideable wiki_tab.is_hidden = True assert wiki_tab['is_hidden'] wiki_tab['is_hidden'] = False assert not wiki_tab.is_hidden
eduNEXT/edunext-platform
lms/djangoapps/course_wiki/tests/test_tab.py
Python
agpl-3.0
2,388
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Neil McAnaspie using IMS Development Environment (version 1.51 build 2480.15886) // Copyright (C) 1995-2006 IMS MAXIMS plc. All rights reserved. package ims.core.forms.vitalsignsbmi; import java.io.Serializable; public final class AccessLogic extends BaseAccessLogic implements Serializable { private static final long serialVersionUID = 1L; public boolean isAccessible() { if(!super.isAccessible()) return false; // TODO: Add your conditions here. return true; } }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Core/src/ims/core/forms/vitalsignsbmi/AccessLogic.java
Java
agpl-3.0
2,406
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.clinical.forms.ttahistorydialog; import ims.framework.*; import ims.framework.controls.*; import ims.framework.enumerations.*; import ims.framework.utils.RuntimeAnchoring; public class GenForm extends FormBridge { private static final long serialVersionUID = 1L; public boolean canProvideData(IReportSeed[] reportSeeds) { return new ReportDataProvider(reportSeeds, this.getFormReportFields()).canProvideData(); } public boolean hasData(IReportSeed[] reportSeeds) { return new ReportDataProvider(reportSeeds, this.getFormReportFields()).hasData(); } public IReportField[] getData(IReportSeed[] reportSeeds) { return getData(reportSeeds, false); } public IReportField[] getData(IReportSeed[] reportSeeds, boolean excludeNulls) { return new ReportDataProvider(reportSeeds, this.getFormReportFields(), excludeNulls).getData(); } private void validateContext(ims.framework.Context context) { if(context == null) return; if(!context.isValidContextType(ims.core.vo.PatientShort.class)) throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.core.vo.PatientShort' of the global context variable 'Core.PatientShort' is not supported."); } private void validateMandatoryContext(Context context) { if(new ims.framework.ContextVariable("Core.PatientShort", "_cvp_Core.PatientShort").getValueIsNull(context)) throw new ims.framework.exceptions.FormMandatoryContextMissingException("The required context data 'Core.PatientShort' is not available."); } public boolean supportsRecordedInError() { return false; } public ims.vo.ValueObject getRecordedInErrorVo() { return null; } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context) throws Exception { setContext(loader, form, appForm, factory, context, Boolean.FALSE, new Integer(0), null, null, new Integer(0)); } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context, Boolean skipContextValidation) throws Exception { setContext(loader, form, appForm, factory, context, skipContextValidation, new Integer(0), null, null, new Integer(0)); } protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, ims.framework.Context context, Boolean skipContextValidation, Integer startControlID, ims.framework.utils.SizeInfo runtimeSize, ims.framework.Control control, Integer startTabIndex) throws Exception { if(loader == null); // this is to avoid eclipse warning only. if(factory == null); // this is to avoid eclipse warning only. if(runtimeSize == null); // this is to avoid eclipse warning only. if(appForm == null) throw new RuntimeException("Invalid application form"); if(startControlID == null) throw new RuntimeException("Invalid startControlID"); if(control == null); // this is to avoid eclipse warning only. if(startTabIndex == null) throw new RuntimeException("Invalid startTabIndex"); this.context = context; this.componentIdentifier = startControlID.toString(); this.formInfo = form.getFormInfo(); this.globalContext = new GlobalContext(context); if(skipContextValidation == null || !skipContextValidation.booleanValue()) { validateContext(context); validateMandatoryContext(context); } super.setContext(form); ims.framework.utils.SizeInfo designSize = new ims.framework.utils.SizeInfo(728, 424); if(runtimeSize == null) runtimeSize = designSize; form.setWidth(runtimeSize.getWidth()); form.setHeight(runtimeSize.getHeight()); super.setGlobalContext(ContextBridgeFlyweightFactory.getInstance().create(GlobalContextBridge.class, context, false)); // Button Controls RuntimeAnchoring anchoringHelper1 = new RuntimeAnchoring(designSize, runtimeSize, 645, 392, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1000), new Integer(anchoringHelper1.getX()), new Integer(anchoringHelper1.getY()), new Integer(anchoringHelper1.getWidth()), new Integer(anchoringHelper1.getHeight()), new Integer(startTabIndex.intValue() + 3), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Cancel", Boolean.FALSE, null, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); RuntimeAnchoring anchoringHelper2 = new RuntimeAnchoring(designSize, runtimeSize, 568, 392, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT); super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1001), new Integer(anchoringHelper2.getX()), new Integer(anchoringHelper2.getY()), new Integer(anchoringHelper2.getWidth()), new Integer(anchoringHelper2.getHeight()), new Integer(startTabIndex.intValue() + 2), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Select", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default })); // Dynamic Grid Controls RuntimeAnchoring anchoringHelper3 = new RuntimeAnchoring(designSize, runtimeSize, 8, 8, 712, 376, ims.framework.enumerations.ControlAnchoring.ALL); super.addControl(factory.getControl(DynamicGrid.class, new Object[] { control, new Integer(startControlID.intValue() + 1002), new Integer(anchoringHelper3.getX()), new Integer(anchoringHelper3.getY()), new Integer(anchoringHelper3.getWidth()), new Integer(anchoringHelper3.getHeight()), new Integer(startTabIndex.intValue() + 1), ControlState.READONLY, ControlState.EDITABLE, ims.framework.enumerations.ControlAnchoring.ALL, null, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE})); } public Button btnCancel() { return (Button)super.getControl(0); } public Button btnSelect() { return (Button)super.getControl(1); } public DynamicGrid dyngrdTTA() { return (DynamicGrid)super.getControl(2); } public GlobalContext getGlobalContext() { return this.globalContext; } public static class GlobalContextBridge extends ContextBridge { private static final long serialVersionUID = 1L; } private IReportField[] getFormReportFields() { if(this.context == null) return null; if(this.reportFields == null) this.reportFields = new ReportFields(this.context, this.formInfo, this.componentIdentifier).getReportFields(); return this.reportFields; } private class ReportFields { public ReportFields(Context context, ims.framework.FormInfo formInfo, String componentIdentifier) { this.context = context; this.formInfo = formInfo; this.componentIdentifier = componentIdentifier; } public IReportField[] getReportFields() { String prefix = formInfo.getLocalVariablesPrefix(); IReportField[] fields = new IReportField[71]; fields[0] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ID", "ID_Patient"); fields[1] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SEX", "Sex"); fields[2] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOB", "Dob"); fields[3] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOD", "Dod"); fields[4] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-RELIGION", "Religion"); fields[5] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISACTIVE", "IsActive"); fields[6] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ETHNICORIGIN", "EthnicOrigin"); fields[7] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-MARITALSTATUS", "MaritalStatus"); fields[8] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SCN", "SCN"); fields[9] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SOURCEOFINFORMATION", "SourceOfInformation"); fields[10] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-TIMEOFDEATH", "TimeOfDeath"); fields[11] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISQUICKREGISTRATIONPATIENT", "IsQuickRegistrationPatient"); fields[12] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-CURRENTRESPONSIBLECONSULTANT", "CurrentResponsibleConsultant"); fields[13] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-ID", "ID_Patient"); fields[14] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-SEX", "Sex"); fields[15] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-DOB", "Dob"); fields[16] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ID", "ID_ClinicalContact"); fields[17] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-SPECIALTY", "Specialty"); fields[18] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CONTACTTYPE", "ContactType"); fields[19] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-STARTDATETIME", "StartDateTime"); fields[20] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ENDDATETIME", "EndDateTime"); fields[21] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CARECONTEXT", "CareContext"); fields[22] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ISCLINICALNOTECREATED", "IsClinicalNoteCreated"); fields[23] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ID", "ID_Hcp"); fields[24] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-HCPTYPE", "HcpType"); fields[25] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISACTIVE", "IsActive"); fields[26] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISHCPARESPONSIBLEHCP", "IsHCPaResponsibleHCP"); fields[27] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISARESPONSIBLEEDCLINICIAN", "IsAResponsibleEDClinician"); fields[28] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ID", "ID_CareContext"); fields[29] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-CONTEXT", "Context"); fields[30] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ORDERINGHOSPITAL", "OrderingHospital"); fields[31] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ESTIMATEDDISCHARGEDATE", "EstimatedDischargeDate"); fields[32] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-STARTDATETIME", "StartDateTime"); fields[33] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ENDDATETIME", "EndDateTime"); fields[34] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-LOCATIONTYPE", "LocationType"); fields[35] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-RESPONSIBLEHCP", "ResponsibleHCP"); fields[36] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ID", "ID_EpisodeOfCare"); fields[37] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-CARESPELL", "CareSpell"); fields[38] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-SPECIALTY", "Specialty"); fields[39] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-RELATIONSHIP", "Relationship"); fields[40] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-STARTDATE", "StartDate"); fields[41] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ENDDATE", "EndDate"); fields[42] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ID", "ID_ClinicalNotes"); fields[43] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALNOTE", "ClinicalNote"); fields[44] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTETYPE", "NoteType"); fields[45] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-DISCIPLINE", "Discipline"); fields[46] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALCONTACT", "ClinicalContact"); fields[47] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISDERIVEDNOTE", "IsDerivedNote"); fields[48] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEW", "ForReview"); fields[49] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline"); fields[50] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-REVIEWINGDATETIME", "ReviewingDateTime"); fields[51] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISCORRECTED", "IsCorrected"); fields[52] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISTRANSCRIBED", "IsTranscribed"); fields[53] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-SOURCEOFNOTE", "SourceOfNote"); fields[54] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-RECORDINGDATETIME", "RecordingDateTime"); fields[55] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-INHOSPITALREPORT", "InHospitalReport"); fields[56] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CARECONTEXT", "CareContext"); fields[57] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification"); fields[58] = new ims.framework.ReportField(this.context, "_cvp_STHK.AvailableBedsListFilter", "BO-1014100009-ID", "ID_BedSpaceState"); fields[59] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ID", "ID_PendingEmergencyAdmission"); fields[60] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ADMISSIONSTATUS", "AdmissionStatus"); fields[61] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ID", "ID_InpatientEpisode"); fields[62] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ESTDISCHARGEDATE", "EstDischargeDate"); fields[63] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-ID", "ID_ClinicalNotes"); fields[64] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEW", "ForReview"); fields[65] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline"); fields[66] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification"); fields[67] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-CARECONTEXT", "CareContext"); fields[68] = new ims.framework.ReportField(this.context, "_cvp_Core.PasEvent", "BO-1014100003-ID", "ID_PASEvent"); fields[69] = new ims.framework.ReportField(this.context, "_cvp_Correspondence.CorrespondenceDetails", "BO-1052100001-ID", "ID_CorrespondenceDetails"); fields[70] = new ims.framework.ReportField(this.context, "_cvp_CareUk.CatsReferral", "BO-1004100035-ID", "ID_CatsReferral"); return fields; } protected Context context = null; protected ims.framework.FormInfo formInfo; protected String componentIdentifier; } public String getUniqueIdentifier() { return null; } private Context context = null; private ims.framework.FormInfo formInfo = null; private String componentIdentifier; private GlobalContext globalContext = null; private IReportField[] reportFields = null; }
open-health-hub/openmaxims-linux
openmaxims_workspace/Clinical/src/ims/clinical/forms/ttahistorydialog/GenForm.java
Java
agpl-3.0
19,304
// Stripe info // Plan ID: BASIC_HOSTING_PLAN // Cost: $5.00 per 30 days, no trial // Statement: Hook.io Hosting Plan var hook = require('../lib/resources/hook'); var user = require('../lib/resources/user'); var config = require('../config'); var bodyParser = require('body-parser'); var mergeParams = require('./mergeParams'); var request = require('request'); var billing = require('../lib/resources/billing') var stripe = require('stripe')(config.stripe.secretKey); var billingForm = require('./billingForm'); var addPaymentOption = require('./addPaymentOption'); module['exports'] = function view (opts, callback) { var $ = this.$; var req = opts.request, res = opts.response; $('#addPaymentMethod').attr('data-key', config.stripe.publicKey); bodyParser()(req, res, function bodyParsed(){ mergeParams(req, res, function(){}); var params = req.resource.params; if (!req.isAuthenticated()) { req.session.redirectTo = "/billing"; return res.redirect('/login'); } // TODO: make it so billing information can be captured directly from the /pricing page function showBillings (results, callback) { var count = results.length; function finish () { var _billing = results[0]; // TODO: data bind $('#slider').slider("value", (_billing.amount / 100)); // console.log('databinding', _billing.amount) $('#databind').text(' \ var resource = {}; \ resource.billing = { \ amount: ' + _billing.amount + ' \ };'); if (count === 0) { callback(null); } }; results.forEach(function(item){ // item.destroy(); billingForm(item, function (err, re){ $('.billingForm').append(re); count--; finish(); }); }); }; $('.addPaymentOption').html(addPaymentOption()); // console.log('getting params', params); // if new billing information was posted ( from account page ), add it if (params.addCustomer) { // console.log('adding new customer'); // create a new customer based on email address stripe.customers.create( { email: params.stripeEmail }, function (err, customer) { if (err) { $('.status').html(err.message); } // console.log('new customer created', err, customer); $('.status').html('New billing informationed added!'); // select plan based on user-selected value var _plan = "BASIC_HOSTING_PLAN"; if (params.amount > 500) { _plan = _plan + "_" + (params.amount / 100); } // console.log('attempting to use plan', _plan); stripe.customers.createSubscription(customer.id, { plan: _plan, source: params.stripeToken // source is the token created from checkout.js }, function(err, charge){ if (err) { $('.status').addClass('error'); $('.status').html(err.message); return callback(err, $.html()); } billing.create({ owner: req.user.username, stripeID: customer.id, amount: params.amount, plan: _plan }, function (err, _billing) { // console.log('new billing created', err, _billing); if (err) { $('.status').html(err.message); return callback(null, err.message); } // console.log('added to plan', err, charge); $('.status').html('Billing Information Added! Thank you!'); billing.find({ owner: req.user.username }, function (err, results) { if (err) { $('.status').html(err.message); return callback(err, $.html()); } showBillings(results, function(){ callback(err, $.html()); }); }); }); }); } ); } else { billing.find({ owner: req.user.username }, function (err, results) { if (err) { return callback(null, err.message); } // console.log('billing results', err, results) if (results.length === 0) { var checkOut = ' \ <form action="/billing" method="POST"> \ <input type="hidden" value="true" name="addCustomer"/> \ <script \ src="https://checkout.stripe.com/checkout.js" class="stripe-button" \ data-key="' + config.stripe.publicKey + '" \ data-image="/square-image.png" \ data-name="hook.io hosting" \ data-description="1 Month Basic Hosting ($5.00)" \ data-amount="500" \ data-currency="usd" \ data-bitcoin="true"> \ </script> \ </form> \ '; // $('.billingForm').html('<h3>No Billing Options Found!</h3>' + checkOut); callback(null, $.html()); } else { var _billing = results[0]; showBillings(results, function(){ callback(null, $.html()); }); // $('.billingForm').html(JSON.stringify(_billing, true, 2)); } }); // callback(null, $.html()); } }); };
ljharb/hook.io
view/billing.js
JavaScript
agpl-3.0
5,422
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5007.25751) * WARNING: DO NOT MODIFY the content of this file * Generated on 16/04/2014, 12:31 * */ package ims.chooseandbook.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Barbara Worwood */ public class NtpfApptCancConvVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.chooseandbook.vo.NtpfApptCancConvVo copy(ims.chooseandbook.vo.NtpfApptCancConvVo valueObjectDest, ims.chooseandbook.vo.NtpfApptCancConvVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_Conversation(valueObjectSrc.getID_Conversation()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // dummy valueObjectDest.setDummy(valueObjectSrc.getDummy()); // cid valueObjectDest.setCid(valueObjectSrc.getCid()); // current valueObjectDest.setCurrent(valueObjectSrc.getCurrent()); // points valueObjectDest.setPoints(valueObjectSrc.getPoints()); // msgUids valueObjectDest.setMsgUids(valueObjectSrc.getMsgUids()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createNtpfApptCancConvVoCollectionFromNtfyApptCancConv(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.choose_book.domain.objects.NtfyApptCancConv objects. */ public static ims.chooseandbook.vo.NtpfApptCancConvVoCollection createNtpfApptCancConvVoCollectionFromNtfyApptCancConv(java.util.Set domainObjectSet) { return createNtpfApptCancConvVoCollectionFromNtfyApptCancConv(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.choose_book.domain.objects.NtfyApptCancConv objects. */ public static ims.chooseandbook.vo.NtpfApptCancConvVoCollection createNtpfApptCancConvVoCollectionFromNtfyApptCancConv(DomainObjectMap map, java.util.Set domainObjectSet) { ims.chooseandbook.vo.NtpfApptCancConvVoCollection voList = new ims.chooseandbook.vo.NtpfApptCancConvVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.choose_book.domain.objects.NtfyApptCancConv domainObject = (ims.choose_book.domain.objects.NtfyApptCancConv) iterator.next(); ims.chooseandbook.vo.NtpfApptCancConvVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.choose_book.domain.objects.NtfyApptCancConv objects. */ public static ims.chooseandbook.vo.NtpfApptCancConvVoCollection createNtpfApptCancConvVoCollectionFromNtfyApptCancConv(java.util.List domainObjectList) { return createNtpfApptCancConvVoCollectionFromNtfyApptCancConv(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.choose_book.domain.objects.NtfyApptCancConv objects. */ public static ims.chooseandbook.vo.NtpfApptCancConvVoCollection createNtpfApptCancConvVoCollectionFromNtfyApptCancConv(DomainObjectMap map, java.util.List domainObjectList) { ims.chooseandbook.vo.NtpfApptCancConvVoCollection voList = new ims.chooseandbook.vo.NtpfApptCancConvVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.choose_book.domain.objects.NtfyApptCancConv domainObject = (ims.choose_book.domain.objects.NtfyApptCancConv) domainObjectList.get(i); ims.chooseandbook.vo.NtpfApptCancConvVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.choose_book.domain.objects.NtfyApptCancConv set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractNtfyApptCancConvSet(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.NtpfApptCancConvVoCollection voCollection) { return extractNtfyApptCancConvSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractNtfyApptCancConvSet(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.NtpfApptCancConvVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.chooseandbook.vo.NtpfApptCancConvVo vo = voCollection.get(i); ims.choose_book.domain.objects.NtfyApptCancConv domainObject = NtpfApptCancConvVoAssembler.extractNtfyApptCancConv(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.choose_book.domain.objects.NtfyApptCancConv list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractNtfyApptCancConvList(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.NtpfApptCancConvVoCollection voCollection) { return extractNtfyApptCancConvList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractNtfyApptCancConvList(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.NtpfApptCancConvVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.chooseandbook.vo.NtpfApptCancConvVo vo = voCollection.get(i); ims.choose_book.domain.objects.NtfyApptCancConv domainObject = NtpfApptCancConvVoAssembler.extractNtfyApptCancConv(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.choose_book.domain.objects.NtfyApptCancConv object. * @param domainObject ims.choose_book.domain.objects.NtfyApptCancConv */ public static ims.chooseandbook.vo.NtpfApptCancConvVo create(ims.choose_book.domain.objects.NtfyApptCancConv domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.choose_book.domain.objects.NtfyApptCancConv object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.chooseandbook.vo.NtpfApptCancConvVo create(DomainObjectMap map, ims.choose_book.domain.objects.NtfyApptCancConv domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.chooseandbook.vo.NtpfApptCancConvVo valueObject = (ims.chooseandbook.vo.NtpfApptCancConvVo) map.getValueObject(domainObject, ims.chooseandbook.vo.NtpfApptCancConvVo.class); if ( null == valueObject ) { valueObject = new ims.chooseandbook.vo.NtpfApptCancConvVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.choose_book.domain.objects.NtfyApptCancConv */ public static ims.chooseandbook.vo.NtpfApptCancConvVo insert(ims.chooseandbook.vo.NtpfApptCancConvVo valueObject, ims.choose_book.domain.objects.NtfyApptCancConv domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.choose_book.domain.objects.NtfyApptCancConv */ public static ims.chooseandbook.vo.NtpfApptCancConvVo insert(DomainObjectMap map, ims.chooseandbook.vo.NtpfApptCancConvVo valueObject, ims.choose_book.domain.objects.NtfyApptCancConv domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_Conversation(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // dummy valueObject.setDummy( domainObject.isDummy() ); // cid valueObject.setCid(ims.chooseandbook.vo.domain.ConvIdVoAssembler.create(map, domainObject.getCid()) ); // current valueObject.setCurrent(ims.chooseandbook.vo.domain.SeqPointVoAssembler.create(map, domainObject.getCurrent()) ); // points valueObject.setPoints(ims.chooseandbook.vo.domain.ConvPointVoAssembler.createConvPointVoCollectionFromConvPoint(map, domainObject.getPoints()) ); // msgUids valueObject.setMsgUids(ims.chooseandbook.vo.domain.ConvUidVoAssembler.createConvUidVoCollectionFromConvUid(map, domainObject.getMsgUids()) ); return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.choose_book.domain.objects.NtfyApptCancConv extractNtfyApptCancConv(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.NtpfApptCancConvVo valueObject) { return extractNtfyApptCancConv(domainFactory, valueObject, new HashMap()); } public static ims.choose_book.domain.objects.NtfyApptCancConv extractNtfyApptCancConv(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.NtpfApptCancConvVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_Conversation(); ims.choose_book.domain.objects.NtfyApptCancConv domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.choose_book.domain.objects.NtfyApptCancConv)domMap.get(valueObject); } // ims.chooseandbook.vo.NtpfApptCancConvVo ID_NtfyApptCancConv field is unknown domainObject = new ims.choose_book.domain.objects.NtfyApptCancConv(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_Conversation()); if (domMap.get(key) != null) { return (ims.choose_book.domain.objects.NtfyApptCancConv)domMap.get(key); } domainObject = (ims.choose_book.domain.objects.NtfyApptCancConv) domainFactory.getDomainObject(ims.choose_book.domain.objects.NtfyApptCancConv.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_Conversation()); domainObject.setDummy(valueObject.getDummy()); domainObject.setCid(ims.chooseandbook.vo.domain.ConvIdVoAssembler.extractConvId(domainFactory, valueObject.getCid(), domMap)); // SaveAsRefVO - treated as a refVo in extract methods ims.choose_book.domain.objects.SeqPoint value3 = null; if ( null != valueObject.getCurrent() ) { if (valueObject.getCurrent().getBoId() == null) { if (domMap.get(valueObject.getCurrent()) != null) { value3 = (ims.choose_book.domain.objects.SeqPoint)domMap.get(valueObject.getCurrent()); } } else { value3 = (ims.choose_book.domain.objects.SeqPoint)domainFactory.getDomainObject(ims.choose_book.domain.objects.SeqPoint.class, valueObject.getCurrent().getBoId()); } } domainObject.setCurrent(value3); domainObject.setPoints(ims.chooseandbook.vo.domain.ConvPointVoAssembler.extractConvPointList(domainFactory, valueObject.getPoints(), domainObject.getPoints(), domMap)); domainObject.setMsgUids(ims.chooseandbook.vo.domain.ConvUidVoAssembler.extractConvUidList(domainFactory, valueObject.getMsgUids(), domainObject.getMsgUids(), domMap)); return domainObject; } }
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/chooseandbook/vo/domain/NtpfApptCancConvVoAssembler.java
Java
agpl-3.0
18,022
/* * RapidMiner * * Copyright (C) 2001-2014 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.repository.gui; import java.awt.Component; import java.util.HashMap; import java.util.Map; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JRadioButton; import com.rapidminer.gui.RapidMinerGUI; import com.rapidminer.gui.tools.ResourceActionAdapter; import com.rapidminer.gui.tools.SwingTools; import com.rapidminer.gui.tools.dialogs.MultiPageDialog; import com.rapidminer.repository.RepositoryException; /** A dialog to create new remote or local repositories. * * @author Simon Fischer * */ public class NewRepositoryDialog extends MultiPageDialog { private static final long serialVersionUID = 1L; private final RemoteRepositoryPanel remoteRepositoryPanel = new RemoteRepositoryPanel(); private final LocalRepositoryPanel localRepositoryPanel = new LocalRepositoryPanel(getFinishButton(), true); private final JRadioButton localButton; private final JRadioButton remoteButton; private NewRepositoryDialog() { super(RapidMinerGUI.getMainFrame(), "repositorydialog", true, new Object[]{}); Box firstPage = new Box(BoxLayout.Y_AXIS); ButtonGroup checkBoxGroup = new ButtonGroup(); localButton = new JRadioButton(new ResourceActionAdapter("new_local_repositiory")); remoteButton = new JRadioButton(new ResourceActionAdapter("new_remote_repositiory")); checkBoxGroup.add(localButton); checkBoxGroup.add(remoteButton); firstPage.add(localButton); firstPage.add(remoteButton); firstPage.add(Box.createVerticalGlue()); localButton.setSelected(true); Map<String,Component> cards = new HashMap<String,Component>(); cards.put("first", firstPage); cards.put("remote", remoteRepositoryPanel); cards.put("local", localRepositoryPanel); layoutDefault(cards); } public static void createNew() { NewRepositoryDialog d = new NewRepositoryDialog(); d.setVisible(true); } @Override protected void finish() { try { if (localButton.isSelected()) { localRepositoryPanel.makeRepository(); } else { remoteRepositoryPanel.makeRepository(); } super.finish(); } catch (RepositoryException e) { SwingTools.showSimpleErrorMessage("cannot_create_repository", e); } } @Override protected String getNameForStep(int step) { switch (step) { case 0: return "first"; case 1: if (localButton.isSelected()) { return "local"; } else { return "remote"; } default: throw new IllegalArgumentException("Illegal index: "+step); } } @Override protected boolean isComplete() { return isLastStep(getCurrentStep()); } @Override protected boolean isLastStep(int step) { return step >= 1; } }
rapidminer/rapidminer
src/com/rapidminer/repository/gui/NewRepositoryDialog.java
Java
agpl-3.0
3,542
<?php namespace SuiteCRM\Test\Driver; use Helper\WebDriverHelper; class WebDriver extends \Codeception\Module\WebDriver { public function _initialize() { $config = $this->_getConfig(); $this->config['host'] = $config['host']; $this->config['port'] = $config['port']; parent::_initialize(); } protected function initialWindowSize() { $config = $this->_getConfig(); $width = isset($config['width']) ? $config['width'] : 1920; $height = isset($config['height']) ? $config['height'] : 1080; $this->resizeWindow($width, $height); } public function _afterSuite() { parent::_afterSuite(); } }
dfstrauss/SuiteCRM
tests/SuiteCRM/Test/Driver/WebDriver.php
PHP
agpl-3.0
701
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'iframe', 'ka', { border: 'ჩარჩოს გამოჩენა', noUrl: 'აკრიფეთ iframe-ის URL', scrolling: 'გადახვევის ზოლების დაშვება', title: 'IFrame-ის პარამეტრები', toolbar: 'IFrame' });
longkb/cms1.8rc2
web/theme/default/libraries/ckeditor/plugins/iframe/lang/ka.js
JavaScript
agpl-3.0
468
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Enable Rack::Cache to put a simple HTTP cache in front of your application # Add `rack-cache` to your Gemfile before enabling this. # For large-scale production use, consider using a caching reverse proxy like # NGINX, varnish or squid. # config.action_dispatch.rack_cache = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier config.assets.css_compressor = :sass #config.assets.compress = true #Changed to false 1/3/2013 to work around a bug when trying to deploy. Wanted the new version more than the speed increase #Oddly, did not seem to make a difference, still attempted precompile config.assets.compress = false # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = true # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. # config.log_level = :debug config.log_level = :info # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production. # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
pcai/lims
config/environments/production.rb
Ruby
agpl-3.0
3,597
#!/usr/bin/python # Copyright 2011, Thomas G. Dimiduk # # This file is part of GroupEng. # # Holopy is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Holopy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with GroupEng. If not, see <http://www.gnu.org/licenses/>.
tdimiduk/groupeng
src/__init__.py
Python
agpl-3.0
724
# == Schema Information # # Table name: announcements # # id :integer not null, primary key # title :string # content :text # attachments_count :integer # limit_to_users :text # start_delivering_at :datetime # stop_delivering_at :datetime # created_at :datetime not null # updated_at :datetime not null # module AnnouncementsHelper end
karmahrm/karmahrm
app/helpers/announcements_helper.rb
Ruby
agpl-3.0
440
/* * CompletionList.java * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.console.shell.assist; import com.google.gwt.event.dom.client.*; import com.google.gwt.event.logical.shared.HasSelectionHandlers; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HTMLTable.Cell; import com.google.gwt.user.client.ui.HTMLTable.CellFormatter; import com.google.gwt.user.client.ui.ScrollPanel; import org.rstudio.core.client.Point; import org.rstudio.core.client.Rectangle; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.events.HasSelectionCommitHandlers; import org.rstudio.core.client.events.SelectionCommitEvent; import org.rstudio.core.client.widget.FontSizer; import org.rstudio.studio.client.workbench.views.console.ConsoleResources; class CompletionList<TItem> extends Composite implements HasSelectionCommitHandlers<TItem>, HasSelectionHandlers<TItem> { public class GridMouseHandler implements ClickHandler, MouseMoveHandler { public void onClick(ClickEvent event) { Cell cell = grid_.getCellForEvent(event); if (cell != null) { int rowClicked = cell.getRowIndex(); SelectionCommitEvent.fire(CompletionList.this, items_[rowClicked]); } } public void onMouseMove(MouseMoveEvent event) { if (lastMouseMoveCoordinates_ != null) { if (event.getScreenX() == lastMouseMoveCoordinates_.getX() && event.getScreenY() == lastMouseMoveCoordinates_.getY()) { return; } } lastMouseMoveCoordinates_ = Point.create(event.getScreenX(), event.getScreenY()); if (firstEvent_) { // Want to avoid the bug where the cursor happens to be positioned // where the popup shows up and thus fires a mouse move event; // so even though the user isn't touching the mouse, the selection // changes. firstEvent_ = false; return; } int mousedOverRow = grid_.getRowForEvent(event); if (mousedOverRow >= 0) { setSelectedIndex(mousedOverRow); } } private boolean firstEvent_ = true; private Point lastMouseMoveCoordinates_; } public CompletionList(TItem[] items, int visibleItems, boolean asHtml, boolean allowVerticalShrink) { allowVerticalShrink_ = allowVerticalShrink; styles_ = ConsoleResources.INSTANCE.consoleStyles(); GridEx grid = new GridEx(items.length, 1); for (int i = 0; i < items.length; i++) { if (asHtml) grid.setHTML(i, 0, items[i].toString()); else grid.setText(i, 0, items[i].toString()); } grid.addClickHandler(new GridMouseHandler()); grid.addMouseMoveHandler(new GridMouseHandler()); grid.setStylePrimaryName(styles_.completionGrid()); FontSizer.applyNormalFontSize(grid); scrollPanel_ = new ScrollPanel(); scrollPanel_.getElement().getStyle().setProperty("overflowX", "hidden"); scrollPanel_.add(grid); scrollPanel_.setHeight((visibleItems * 26) + "px"); initWidget(scrollPanel_); grid_ = grid; items_ = items; } @Override protected void onLoad() { super.onLoad(); int width = grid_.getOffsetWidth() + 20; if (maxWidthInPixels_ != null && maxWidthInPixels_ > 0 && maxWidthInPixels_ < width) width = maxWidthInPixels_; scrollPanel_.setWidth(width + "px"); if (allowVerticalShrink_ && grid_.getOffsetHeight() < scrollPanel_.getOffsetHeight()) { scrollPanel_.setHeight(""); } grid_.setWidth("100%"); selectNext(); } public int getItemCount() { if (grid_ != null) return grid_.getRowCount(); else return 0; } public TItem getSelectedItem() { int index = getSelectedIndex(); if (index < 0) return null; return items_[index]; } public boolean selectNext() { return moveSelection(1, true); } public boolean selectPrev() { return moveSelection(-1, true); } public boolean selectNextPage() { return moveSelection(4, false); } public boolean selectPrevPage() { return moveSelection(-4, false); } public boolean selectFirst() { return moveSelection(-getItemCount(), false); } public boolean selectLast() { return moveSelection(getItemCount(), false); } private boolean moveSelection(int offset, boolean allowWrap) { if (getItemCount() == 0) return false; int index = getSelectedIndex() + offset; if (allowWrap) index = (index + getItemCount()) % getItemCount(); else index = Math.min(getItemCount() - 1, Math.max(0, index)); setSelectedIndex(index); return true; } public HandlerRegistration addSelectionHandler( SelectionHandler<TItem> handler) { return addHandler(handler, SelectionEvent.getType()); } public HandlerRegistration addSelectionCommitHandler( SelectionCommitEvent.Handler<TItem> handler) { return addHandler(handler, SelectionCommitEvent.getType()); } public HTML getDetailedInfoPane() { return null; } public int getSelectedIndex() { return selectedIndex_; } public void setSelectedIndex(int index) { if (selectedIndex_ != index) { CellFormatter cf = grid_.getCellFormatter(); if (selectedIndex_ >= 0) cf.removeStyleName(selectedIndex_, 0, styles_.selected()); selectedIndex_ = index; if (index >= 0) { cf.addStyleName(selectedIndex_, 0, styles_.selected()); com.google.gwt.dom.client.Element el = DomUtils.getTableCell(grid_.getElement(), index, 0); DomUtils.ensureVisibleVert(scrollPanel_.getElement(), el, 2); SelectionEvent.fire(this, getSelectedItem()); } } } /** * Gets the rectangle of the selected row in absolute (document-relative) * coordinates, or null if nothing is selected. */ public Rectangle getSelectionRect() { int index = getSelectedIndex(); if (index < 0) return null; com.google.gwt.dom.client.Element el = DomUtils.getTableCell(grid_.getElement(), index, 0); return new Rectangle(el.getAbsoluteLeft(), el.getAbsoluteTop(), el.getOffsetWidth(), el.getOffsetHeight()); } public void setMaxWidth(int maxWidthInPixels) { maxWidthInPixels_ = maxWidthInPixels; } public TItem[] getItems() { return items_; } private int selectedIndex_ = -1; private final GridEx grid_; private final TItem[] items_; private final ScrollPanel scrollPanel_; private final ConsoleResources.ConsoleStyles styles_; private final boolean allowVerticalShrink_; private Integer maxWidthInPixels_; }
JanMarvin/rstudio
src/gwt/src/org/rstudio/studio/client/workbench/views/console/shell/assist/CompletionList.java
Java
agpl-3.0
8,056
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.pathways.forms.eventconfiguration; public abstract class BaseLogic extends Handlers { public final Class getDomainInterface() throws ClassNotFoundException { return ims.pathways.domain.EventConfiguration.class; } public final void setContext(ims.framework.UIEngine engine, GenForm form, ims.pathways.domain.EventConfiguration domain) { setContext(engine, form); this.domain = domain; } public void clearContextInformation() { engine.clearPatientContextInformation(); } protected final void oncmbEventTypeValueSet(Object value) { java.util.ArrayList listOfValues = this.form.cmbEventType().getValues(); if(value == null) { if(listOfValues != null && listOfValues.size() > 0) { for(int x = 0; x < listOfValues.size(); x++) { ims.pathways.vo.lookups.EventCreationType existingInstance = (ims.pathways.vo.lookups.EventCreationType)listOfValues.get(x); if(!existingInstance.isActive()) { bindcmbEventTypeLookup(); return; } } } } else if(value instanceof ims.pathways.vo.lookups.EventCreationType) { ims.pathways.vo.lookups.EventCreationType instance = (ims.pathways.vo.lookups.EventCreationType)value; if(listOfValues != null) { if(listOfValues.size() == 0) bindcmbEventTypeLookup(); for(int x = 0; x < listOfValues.size(); x++) { ims.pathways.vo.lookups.EventCreationType existingInstance = (ims.pathways.vo.lookups.EventCreationType)listOfValues.get(x); if(existingInstance.equals(instance)) return; } } this.form.cmbEventType().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor()); } } protected final void bindcmbEventTypeLookup() { this.form.cmbEventType().clear(); ims.pathways.vo.lookups.EventCreationTypeCollection lookupCollection = ims.pathways.vo.lookups.LookupHelper.getEventCreationType(this.domain.getLookupService()); for(int x = 0; x < lookupCollection.size(); x++) { this.form.cmbEventType().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor()); } } protected final void setcmbEventTypeLookupValue(int id) { ims.pathways.vo.lookups.EventCreationType instance = ims.pathways.vo.lookups.LookupHelper.getEventCreationTypeInstance(this.domain.getLookupService(), id); if(instance != null) this.form.cmbEventType().setValue(instance); } protected final void defaultcmbEventTypeLookupValue() { this.form.cmbEventType().setValue((ims.pathways.vo.lookups.EventCreationType)domain.getLookupService().getDefaultInstance(ims.pathways.vo.lookups.EventCreationType.class, engine.getFormName().getID(), ims.pathways.vo.lookups.EventCreationType.TYPE_ID)); } protected final void oncmbStatusValueSet(Object value) { java.util.ArrayList listOfValues = this.form.cmbStatus().getValues(); if(value == null) { if(listOfValues != null && listOfValues.size() > 0) { for(int x = 0; x < listOfValues.size(); x++) { ims.core.vo.lookups.PreActiveActiveInactiveStatus existingInstance = (ims.core.vo.lookups.PreActiveActiveInactiveStatus)listOfValues.get(x); if(!existingInstance.isActive()) { bindcmbStatusLookup(); return; } } } } else if(value instanceof ims.core.vo.lookups.PreActiveActiveInactiveStatus) { ims.core.vo.lookups.PreActiveActiveInactiveStatus instance = (ims.core.vo.lookups.PreActiveActiveInactiveStatus)value; if(listOfValues != null) { if(listOfValues.size() == 0) bindcmbStatusLookup(); for(int x = 0; x < listOfValues.size(); x++) { ims.core.vo.lookups.PreActiveActiveInactiveStatus existingInstance = (ims.core.vo.lookups.PreActiveActiveInactiveStatus)listOfValues.get(x); if(existingInstance.equals(instance)) return; } } this.form.cmbStatus().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor()); } } protected final void bindcmbStatusLookup() { this.form.cmbStatus().clear(); ims.core.vo.lookups.PreActiveActiveInactiveStatusCollection lookupCollection = ims.core.vo.lookups.LookupHelper.getPreActiveActiveInactiveStatus(this.domain.getLookupService()); for(int x = 0; x < lookupCollection.size(); x++) { this.form.cmbStatus().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor()); } } protected final void setcmbStatusLookupValue(int id) { ims.core.vo.lookups.PreActiveActiveInactiveStatus instance = ims.core.vo.lookups.LookupHelper.getPreActiveActiveInactiveStatusInstance(this.domain.getLookupService(), id); if(instance != null) this.form.cmbStatus().setValue(instance); } protected final void defaultcmbStatusLookupValue() { this.form.cmbStatus().setValue((ims.core.vo.lookups.PreActiveActiveInactiveStatus)domain.getLookupService().getDefaultInstance(ims.core.vo.lookups.PreActiveActiveInactiveStatus.class, engine.getFormName().getID(), ims.core.vo.lookups.PreActiveActiveInactiveStatus.TYPE_ID)); } protected final void bindgrdExternalEventMappingsColStatusLookup() { this.form.lyrTargets().tabExternalMappings().grdExternalEventMappings().ColStatusComboBox().clear(); ims.core.vo.lookups.PreActiveActiveInactiveStatusCollection lookupCollection = ims.core.vo.lookups.LookupHelper.getPreActiveActiveInactiveStatus(this.domain.getLookupService()); for(int x = 0; x < lookupCollection.size(); x++) { this.form.lyrTargets().tabExternalMappings().grdExternalEventMappings().ColStatusComboBox().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor()); } } protected final void bindgrdRTTColActionLookup() { this.form.lyrTargets().tabRTT().grdRTT().ColActionComboBox().clear(); ims.pathways.vo.lookups.RTTActionCollection lookupCollection = ims.pathways.vo.lookups.LookupHelper.getRTTAction(this.domain.getLookupService()); for(int x = 0; x < lookupCollection.size(); x++) { this.form.lyrTargets().tabRTT().grdRTT().ColActionComboBox().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor()); } } protected final void bindgrdRTTColStatusLookup() { this.form.lyrTargets().tabRTT().grdRTT().ColStatusComboBox().clear(); ims.core.vo.lookups.PreActiveActiveInactiveStatusCollection lookupCollection = ims.core.vo.lookups.LookupHelper.getPreActiveActiveInactiveStatus(this.domain.getLookupService()); for(int x = 0; x < lookupCollection.size(); x++) { this.form.lyrTargets().tabRTT().grdRTT().ColStatusComboBox().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor()); } } protected final void oncmbTypeValueSet(Object value) { java.util.ArrayList listOfValues = this.form.cmbType().getValues(); if(value == null) { if(listOfValues != null && listOfValues.size() > 0) { for(int x = 0; x < listOfValues.size(); x++) { ims.scheduling.vo.lookups.Status_Reason existingInstance = (ims.scheduling.vo.lookups.Status_Reason)listOfValues.get(x); if(!existingInstance.isActive()) { bindcmbTypeLookup(); return; } } } } else if(value instanceof ims.scheduling.vo.lookups.Status_Reason) { ims.scheduling.vo.lookups.Status_Reason instance = (ims.scheduling.vo.lookups.Status_Reason)value; if(listOfValues != null) { if(listOfValues.size() == 0) bindcmbTypeLookup(); for(int x = 0; x < listOfValues.size(); x++) { ims.scheduling.vo.lookups.Status_Reason existingInstance = (ims.scheduling.vo.lookups.Status_Reason)listOfValues.get(x); if(existingInstance.equals(instance)) return; } } this.form.cmbType().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor()); } } protected final void bindcmbTypeLookup() { this.form.cmbType().clear(); ims.scheduling.vo.lookups.Status_ReasonCollection lookupCollection = ims.scheduling.vo.lookups.LookupHelper.getStatus_Reason(this.domain.getLookupService()); for(int x = 0; x < lookupCollection.size(); x++) { this.form.cmbType().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor()); } } protected final void setcmbTypeLookupValue(int id) { ims.scheduling.vo.lookups.Status_Reason instance = ims.scheduling.vo.lookups.LookupHelper.getStatus_ReasonInstance(this.domain.getLookupService(), id); if(instance != null) this.form.cmbType().setValue(instance); } protected final void defaultcmbTypeLookupValue() { this.form.cmbType().setValue((ims.scheduling.vo.lookups.Status_Reason)domain.getLookupService().getDefaultInstance(ims.scheduling.vo.lookups.Status_Reason.class, engine.getFormName().getID(), ims.scheduling.vo.lookups.Status_Reason.TYPE_ID)); } protected final void oncmbReasonValueSet(Object value) { java.util.ArrayList listOfValues = this.form.cmbReason().getValues(); if(value == null) { if(listOfValues != null && listOfValues.size() > 0) { for(int x = 0; x < listOfValues.size(); x++) { ims.scheduling.vo.lookups.CancelAppointmentReason existingInstance = (ims.scheduling.vo.lookups.CancelAppointmentReason)listOfValues.get(x); if(!existingInstance.isActive()) { bindcmbReasonLookup(); return; } } } } else if(value instanceof ims.scheduling.vo.lookups.CancelAppointmentReason) { ims.scheduling.vo.lookups.CancelAppointmentReason instance = (ims.scheduling.vo.lookups.CancelAppointmentReason)value; if(listOfValues != null) { if(listOfValues.size() == 0) bindcmbReasonLookup(); for(int x = 0; x < listOfValues.size(); x++) { ims.scheduling.vo.lookups.CancelAppointmentReason existingInstance = (ims.scheduling.vo.lookups.CancelAppointmentReason)listOfValues.get(x); if(existingInstance.equals(instance)) return; } } this.form.cmbReason().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor()); } } protected final void bindcmbReasonLookup() { this.form.cmbReason().clear(); ims.scheduling.vo.lookups.CancelAppointmentReasonCollection lookupCollection = ims.scheduling.vo.lookups.LookupHelper.getCancelAppointmentReason(this.domain.getLookupService()); for(int x = 0; x < lookupCollection.size(); x++) { this.form.cmbReason().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor()); } } protected final void setcmbReasonLookupValue(int id) { ims.scheduling.vo.lookups.CancelAppointmentReason instance = ims.scheduling.vo.lookups.LookupHelper.getCancelAppointmentReasonInstance(this.domain.getLookupService(), id); if(instance != null) this.form.cmbReason().setValue(instance); } protected final void defaultcmbReasonLookupValue() { this.form.cmbReason().setValue((ims.scheduling.vo.lookups.CancelAppointmentReason)domain.getLookupService().getDefaultInstance(ims.scheduling.vo.lookups.CancelAppointmentReason.class, engine.getFormName().getID(), ims.scheduling.vo.lookups.CancelAppointmentReason.TYPE_ID)); } public final void free() { super.free(); domain = null; } protected ims.pathways.domain.EventConfiguration domain; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Pathways/src/ims/pathways/forms/eventconfiguration/BaseLogic.java
Java
agpl-3.0
13,907
<?php /** * @author Georg Ehrke <georg@owncloud.com> * @author Joas Schilling <nickvergessen@owncloud.com> * @author josh4trunks <joshruehlig@gmail.com> * @author Olivier Paroz <github@oparoz.com> * @author Robin Appelman <icewind@owncloud.com> * @author Thomas Müller <thomas.mueller@tmit.eu> * @author Thomas Tanghus <thomas@tanghus.net> * * @copyright Copyright (c) 2016, ownCloud, Inc. * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\Preview; abstract class Image extends Provider { /** * {@inheritDoc} */ public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) { //get fileinfo $fileInfo = $fileview->getFileInfo($path); if (!$fileInfo) { return false; } $maxSizeForImages = \OC::$server->getConfig()->getSystemValue('preview_max_filesize_image', 50); $size = $fileInfo->getSize(); if ($maxSizeForImages !== -1 && $size > ($maxSizeForImages * 1024 * 1024)) { return false; } $image = new \OC_Image(); $useTempFile = $fileInfo->isEncrypted() || !$fileInfo->getStorage()->isLocal(); if ($useTempFile) { $fileName = $fileview->toTmpFile($path); } else { $fileName = $fileview->getLocalFile($path); } $image->loadFromFile($fileName); $image->fixOrientation(); if ($useTempFile) { unlink($fileName); } if ($image->valid()) { $image->scaleDownToFit($maxX, $maxY); return $image; } return false; } }
bluelml/core
lib/private/Preview/Image.php
PHP
agpl-3.0
2,008
require "rails_helper" describe TextHelper do describe "#first_paragraph" do it "returns the first paragraph of a text" do text = "\n\nThis is the first paragraph\n\nThis is the second paragraph\n" expect(first_paragraph(text)).to eq("This is the first paragraph") end it "returns blank if the text is blank" do expect(first_paragraph("")).to eq("") expect(first_paragraph(nil)).to eq("") end end end
consul/consul
spec/helpers/text_helper_spec.rb
Ruby
agpl-3.0
447
# Configure SQL server so it accepts TCP connections on the AppVeyor # CI platfrom. # # Pass the script the instanceName and tcpPort # # See # http://www.appveyor.com/docs/services-databases#enabling-tcp-ip-named-pipes-and-setting-instance-alias # https://gist.githubusercontent.com/FeodorFitsner/d971c5a98782d211640d/raw/sql-server-ip-and-alias.ps1 # http://geekswithblogs.net/TedStatham/archive/2014/06/13/setting-the-ports-for-a-named-sql-server-instance-using.aspx Param( [string]$instanceName, [string]$tcpPort ) [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement") | Out-Null $serverName = $env:COMPUTERNAME $smo = 'Microsoft.SqlServer.Management.Smo.' $wmi = new-object ($smo + 'Wmi.ManagedComputer') # Enable TCP/IP $uri = "ManagedComputer[@Name='$serverName']/ServerInstance[@Name='$instanceName']/ServerProtocol[@Name='Tcp']" $Tcp = $wmi.GetSmoObject($uri) $Tcp.IsEnabled = $true foreach ($ipAddress in $Tcp.IPAddresses) { $ipAddress.IPAddressProperties["TcpDynamicPorts"].Value = "" $ipAddress.IPAddressProperties["TcpPort"].Value = $tcpPort } $Tcp.alter() # Service needs to be restarted # Restart service Restart-Service "MSSQL`$$instanceName"
vlifesystems/rulehuntersrv
ci/sql-server-activate-tcp-fixed-port.ps1
PowerShell
agpl-3.0
1,284
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_22) on Thu May 24 19:39:42 WET 2012 --> <TITLE> org.apache.jmeter.report.writers Class Hierarchy (Apache JMeter API) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="org.apache.jmeter.report.writers Class Hierarchy (Apache JMeter API)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <b>Apache JMeter</b></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/jmeter/report/gui/tree/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/jmeter/report/writers/gui/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/jmeter/report/writers/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> Hierarchy For Package org.apache.jmeter.report.writers </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B><DD><A HREF="../../../../../overview-tree.html">All Packages</A></DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">java.lang.<A HREF="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html" title="class or interface in java.lang"><B>Object</B></A><UL> <LI TYPE="circle">org.apache.jmeter.testelement.<A HREF="../../../../../org/apache/jmeter/testelement/AbstractTestElement.html" title="class in org.apache.jmeter.testelement"><B>AbstractTestElement</B></A> (implements org.apache.jmeter.gui.<A HREF="../../../../../org/apache/jmeter/gui/Searchable.html" title="interface in org.apache.jmeter.gui">Searchable</A>, java.io.<A HREF="http://download.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html" title="class or interface in java.io">Serializable</A>, org.apache.jmeter.testelement.<A HREF="../../../../../org/apache/jmeter/testelement/TestElement.html" title="interface in org.apache.jmeter.testelement">TestElement</A>) <UL> <LI TYPE="circle">org.apache.jmeter.report.writers.<A HREF="../../../../../org/apache/jmeter/report/writers/AbstractReportWriter.html" title="class in org.apache.jmeter.report.writers"><B>AbstractReportWriter</B></A> (implements org.apache.jmeter.report.writers.<A HREF="../../../../../org/apache/jmeter/report/writers/ReportWriter.html" title="interface in org.apache.jmeter.report.writers">ReportWriter</A>) <UL> <LI TYPE="circle">org.apache.jmeter.report.writers.<A HREF="../../../../../org/apache/jmeter/report/writers/HTMLReportWriter.html" title="class in org.apache.jmeter.report.writers"><B>HTMLReportWriter</B></A></UL> </UL> <LI TYPE="circle">org.apache.jmeter.report.writers.<A HREF="../../../../../org/apache/jmeter/report/writers/DefaultPageSummary.html" title="class in org.apache.jmeter.report.writers"><B>DefaultPageSummary</B></A> (implements org.apache.jmeter.report.writers.<A HREF="../../../../../org/apache/jmeter/report/writers/PageSummary.html" title="interface in org.apache.jmeter.report.writers">PageSummary</A>) <LI TYPE="circle">org.apache.jmeter.report.writers.<A HREF="../../../../../org/apache/jmeter/report/writers/DefaultReportSummary.html" title="class in org.apache.jmeter.report.writers"><B>DefaultReportSummary</B></A> (implements org.apache.jmeter.report.writers.<A HREF="../../../../../org/apache/jmeter/report/writers/ReportSummary.html" title="interface in org.apache.jmeter.report.writers">ReportSummary</A>) </UL> </UL> <H2> Interface Hierarchy </H2> <UL> <LI TYPE="circle">java.lang.<A HREF="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Cloneable.html" title="class or interface in java.lang"><B>Cloneable</B></A><UL> <LI TYPE="circle">org.apache.jmeter.report.writers.<A HREF="../../../../../org/apache/jmeter/report/writers/PageSummary.html" title="interface in org.apache.jmeter.report.writers"><B>PageSummary</B></A><LI TYPE="circle">org.apache.jmeter.report.writers.<A HREF="../../../../../org/apache/jmeter/report/writers/ReportSummary.html" title="interface in org.apache.jmeter.report.writers"><B>ReportSummary</B></A></UL> <LI TYPE="circle">org.apache.jmeter.report.writers.<A HREF="../../../../../org/apache/jmeter/report/writers/ReportWriter.html" title="interface in org.apache.jmeter.report.writers"><B>ReportWriter</B></A></UL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <b>Apache JMeter</b></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/jmeter/report/gui/tree/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/jmeter/report/writers/gui/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/jmeter/report/writers/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#xA9; 1998-2012 Apache Software Foundation. All Rights Reserved. </BODY> </HTML>
telefonicaid/notification_server
test/jmeter/apache-jmeter-2.7/docs/api/org/apache/jmeter/report/writers/package-tree.html
HTML
agpl-3.0
8,999