Search Results: "oku"

8 January 2011

Nikita Youshchenko: Psi+

Just discovered Psi+ project. It is a fork of well-known Psi jabber client, with many improvements and new features. Among others things, Psi+ implements plugins feature, and comes with several interesting and useful plugins. One of those provides anti-spam protection, and other is designed specifically for ICQ users. Psi+ is a drop-in replacement for Psi, it uses same per-user configuration. Package is available for Debian Squeze, so if you are already running that version, just run
aptitude install psi-plus psi-plus-plugins
Then restart Psi and enjoy :) .

31 December 2010

Lars Wirzenius: Micro-optimizing btree

Benchmark results before:
num_operations: 1000000
insert      : 191.090 s (  5238.3/s) CPU; 191.106 s (  5237.7/s) wall clock
lookup      : 30.430 s ( 33068.8/s) CPU; 30.428 s ( 33064.0/s) wall clock
lookup_range: 85.700 s ( 11694.5/s) CPU; 85.700 s ( 11693.6/s) wall clock
insert2     : 143.320 s (  6986.7/s) CPU; 143.315 s (  6986.6/s) wall clock
remove      : 246.010 s (  4068.0/s) CPU; 246.013 s (  4067.9/s) wall clock
remove_range: 225.210 s (  4444.0/s) CPU; 225.286 s (  4442.4/s) wall clock
That's insert, lookup, and remove operations (and range operations) on a B-tree with one million keys. insert2 is insertions where keys are sorted. All nodes are stored in memory, not on disk. After some micro-optimization (replacing my own flexible bsearch implementation with the Python standard library one):
num_operations: 1000000
insert      : 97.850 s ( 10237.5/s) CPU; 97.860 s ( 10237.1/s) wall clock
lookup      : 12.430 s ( 81566.1/s) CPU; 12.429 s ( 81609.8/s) wall clock
lookup_range: 52.670 s ( 19047.6/s) CPU; 52.669 s ( 19050.0/s) wall clock
insert2     : 72.600 s ( 13806.4/s) CPU; 72.595 s ( 13808.6/s) wall clock
remove      : 134.510 s (  7443.8/s) CPU; 134.512 s (  7444.0/s) wall clock
remove_range: 169.740 s (  5897.3/s) CPU; 169.795 s (  5895.6/s) wall clock
Not bad, for a train ride's work, with some additional improvements late at night in a hotel room. Code is clearer too, now, at least mostly. And there's less of it: duplicating standard library functionality always maks me feel icky. The numbers for removals look bad, really bad. Espcially range removal should be much better. If anyone wanted to get familiar with my btree code base, that would be an excellent place to start from. See the README for instructions.

27 December 2010

Petter Reinholdtsen: The many definitions of a open standard

One of the reasons I like the Digistan definition of "Free and Open Standard" is that this is a new term, and thus the meaning of the term has been decided by Digistan. The term "Open Standard" has become so misunderstood that it is no longer very useful when talking about standards. One end up discussing which definition is the best one and with such frame the only one gaining are the proponents of de-facto standards and proprietary solutions. But to give us an idea about the diversity of definitions of open standards, here are a few that I know about. This list is not complete, but can be a starting point for those that want to do a complete survey. More definitions are available on the wikipedia page. First off is my favourite, the definition from the European Interoperability Framework version 1.0. Really sad to notice that BSA and others has succeeded in getting it removed from version 2.0 of the framework by stacking the committee drafting the new version with their own people. Anyway, the definition is still available and it include the key properties needed to make sure everyone can use a specification on equal terms.
The following are the minimal characteristics that a specification and its attendant documents must have in order to be considered an open standard:
  • The standard is adopted and will be maintained by a not-for-profit organisation, and its ongoing development occurs on the basis of an open decision-making procedure available to all interested parties (consensus or majority decision etc.).
  • The standard has been published and the standard specification document is available either freely or at a nominal charge. It must be permissible to all to copy, distribute and use it for no fee or at a nominal fee.
  • The intellectual property - i.e. patents possibly present - of (parts of) the standard is made irrevocably available on a royalty- free basis.
  • There are no constraints on the re-use of the standard.
Another one originates from my friends over at DKUUG, who coined and gathered support for this definition in 2004. It even made it into the Danish parlament as their definition of a open standard. Another from a different part of the Danish government is available from the wikipedia page.
En ben standard opfylder f lgende krav:
  1. Veldokumenteret med den fuldst ndige specifikation offentligt tilg ngelig.
  2. Frit implementerbar uden konomiske, politiske eller juridiske begr nsninger p implementation og anvendelse.
  3. Standardiseret og vedligeholdt i et bent forum (en s kaldt "standardiseringsorganisation") via en ben proces.
Then there is the definition from Free Software Foundation Europe.
An Open Standard refers to a format or protocol that is
  1. subject to full public assessment and use without constraints in a manner equally available to all parties;
  2. without any components or extensions that have dependencies on formats or protocols that do not meet the definition of an Open Standard themselves;
  3. free from legal or technical clauses that limit its utilisation by any party or in any business model;
  4. managed and further developed independently of any single vendor in a process open to the equal participation of competitors and third parties;
  5. available in multiple complete implementations by competing vendors, or as a complete implementation equally available to all parties.
A long time ago, SUN Microsystems, now bought by Oracle, created its Open Standards Checklist with a fairly detailed description.
Creation and Management of an Open Standard
  • Its development and management process must be collaborative and democratic:
    • Participation must be accessible to all those who wish to participate and can meet fair and reasonable criteria imposed by the organization under which it is developed and managed.
    • The processes must be documented and, through a known method, can be changed through input from all participants.
    • The process must be based on formal and binding commitments for the disclosure and licensing of intellectual property rights.
    • Development and management should strive for consensus, and an appeals process must be clearly outlined.
    • The standard specification must be open to extensive public review at least once in its life-cycle, with comments duly discussed and acted upon, if required.
Use and Licensing of an Open Standard
  • The standard must describe an interface, not an implementation, and the industry must be capable of creating multiple, competing implementations to the interface described in the standard without undue or restrictive constraints. Interfaces include APIs, protocols, schemas, data formats and their encoding.
  • The standard must not contain any proprietary "hooks" that create a technical or economic barriers
  • Faithful implementations of the standard must interoperate. Interoperability means the ability of a computer program to communicate and exchange information with other computer programs and mutually to use the information which has been exchanged. This includes the ability to use, convert, or exchange file formats, protocols, schemas, interface information or conventions, so as to permit the computer program to work with other computer programs and users in all the ways in which they are intended to function.
  • It must be permissible for anyone to copy, distribute and read the standard for a nominal fee, or even no fee. If there is a fee, it must be low enough to not preclude widespread use.
  • It must be possible for anyone to obtain free (no royalties or fees; also known as "royalty free"), worldwide, non-exclusive and perpetual licenses to all essential patent claims to make, use and sell products based on the standard. The only exceptions are terminations per the reciprocity and defensive suspension terms outlined below. Essential patent claims include pending, unpublished patents, published patents, and patent applications. The license is only for the exact scope of the standard in question.
    • May be conditioned only on reciprocal licenses to any of licensees' patent claims essential to practice that standard (also known as a reciprocity clause)
    • May be terminated as to any licensee who sues the licensor or any other licensee for infringement of patent claims essential to practice that standard (also known as a "defensive suspension" clause)
    • The same licensing terms are available to every potential licensor
  • The licensing terms of an open standards must not preclude implementations of that standard under open source licensing terms or restricted licensing terms
It is said that one of the nice things about standards is that there are so many of them. As you can see, the same holds true for open standard definitions. Most of the definitions have a lot in common, and it is not really controversial what properties a open standard should have, but the diversity of definitions have made it possible for those that want to avoid a level marked field and real competition to downplay the significance of open standards. I hope we can turn this tide by focusing on the advantages of Free and Open Standards.

25 December 2010

Petter Reinholdtsen: The reply from Edgar Villanueva to Microsoft in Peru

A few days ago an article in the Norwegian Computerworld magazine about how version 2.0 of European Interoperability Framework has been successfully lobbied by the proprietary software industry to remove the focus on free software. Nothing very surprising there, given earlier reports on how Microsoft and others have stacked the committees in this work. But I find this very sad. The definition of an open standard from version 1 was very good, and something I believe should be used also in the future, alongside the definition from Digistan. Version 2 have removed the open standard definition from its content. Anyway, the news reminded me of the great reply sent by Dr. Edgar Villanueva, congressman in Peru at the time, to Microsoft as a reply to Microsofts attack on his proposal regarding the use of free software in the public sector in Peru. As the text was not available from a few of the URLs where it used to be available, I copy it here from my source to ensure it is available also in the future. Some background information about that story is available in an article from Linux Journal in 2002.
Lima, 8th of April, 2002
To: Se or JUAN ALBERTO GONZ LEZ
General Manager of Microsoft Per Dear Sir: First of all, I thank you for your letter of March 25, 2002 in which you state the official position of Microsoft relative to Bill Number 1609, Free Software in Public Administration, which is indubitably inspired by the desire for Peru to find a suitable place in the global technological context. In the same spirit, and convinced that we will find the best solutions through an exchange of clear and open ideas, I will take this opportunity to reply to the commentaries included in your letter. While acknowledging that opinions such as yours constitute a significant contribution, it would have been even more worthwhile for me if, rather than formulating objections of a general nature (which we will analyze in detail later) you had gathered solid arguments for the advantages that proprietary software could bring to the Peruvian State, and to its citizens in general, since this would have allowed a more enlightening exchange in respect of each of our positions. With the aim of creating an orderly debate, we will assume that what you call "open source software" is what the Bill defines as "free software", since there exists software for which the source code is distributed together with the program, but which does not fall within the definition established by the Bill; and that what you call "commercial software" is what the Bill defines as "proprietary" or "unfree", given that there exists free software which is sold in the market for a price like any other good or service. It is also necessary to make it clear that the aim of the Bill we are discussing is not directly related to the amount of direct savings that can by made by using free software in state institutions. That is in any case a marginal aggregate value, but in no way is it the chief focus of the Bill. The basic principles which inspire the Bill are linked to the basic guarantees of a state of law, such as:
  • Free access to public information by the citizen.
  • Permanence of public data.
  • Security of the State and citizens.
To guarantee the free access of citizens to public information, it is indispensable that the encoding of data is not tied to a single provider. The use of standard and open formats gives a guarantee of this free access, if necessary through the creation of compatible free software. To guarantee the permanence of public data, it is necessary that the usability and maintenance of the software does not depend on the goodwill of the suppliers, or on the monopoly conditions imposed by them. For this reason the State needs systems the development of which can be guaranteed due to the availability of the source code. To guarantee national security or the security of the State, it is indispensable to be able to rely on systems without elements which allow control from a distance or the undesired transmission of information to third parties. Systems with source code freely accessible to the public are required to allow their inspection by the State itself, by the citizens, and by a large number of independent experts throughout the world. Our proposal brings further security, since the knowledge of the source code will eliminate the growing number of programs with *spy code*. In the same way, our proposal strengthens the security of the citizens, both in their role as legitimate owners of information managed by the state, and in their role as consumers. In this second case, by allowing the growth of a widespread availability of free software not containing *spy code* able to put at risk privacy and individual freedoms. In this sense, the Bill is limited to establishing the conditions under which the state bodies will obtain software in the future, that is, in a way compatible with these basic principles. From reading the Bill it will be clear that once passed:
  • the law does not forbid the production of proprietary software
  • the law does not forbid the sale of proprietary software
  • the law does not specify which concrete software to use
  • the law does not dictate the supplier from whom software will be bought
  • the law does not limit the terms under which a software product can be licensed.
  • What the Bill does express clearly, is that, for software to be acceptable for the state it is not enough that it is technically capable of fulfilling a task, but that further the contractual conditions must satisfy a series of requirements regarding the license, without which the State cannot guarantee the citizen adequate processing of his data, watching over its integrity, confidentiality, and accessibility throughout time, as these are very critical aspects for its normal functioning. We agree, Mr. Gonzalez, that information and communication technology have a significant impact on the quality of life of the citizens (whether it be positive or negative). We surely also agree that the basic values I have pointed out above are fundamental in a democratic state like Peru. So we are very interested to know of any other way of guaranteeing these principles, other than through the use of free software in the terms defined by the Bill. As for the observations you have made, we will now go on to analyze them in detail: Firstly, you point out that: "1. The bill makes it compulsory for all public bodies to use only free software, that is to say open source software, which breaches the principles of equality before the law, that of non-discrimination and the right of free private enterprise, freedom of industry and of contract, protected by the constitution." This understanding is in error. The Bill in no way affects the rights you list; it limits itself entirely to establishing conditions for the use of software on the part of state institutions, without in any way meddling in private sector transactions. It is a well established principle that the State does not enjoy the wide spectrum of contractual freedom of the private sector, as it is limited in its actions precisely by the requirement for transparency of public acts; and in this sense, the preservation of the greater common interest must prevail when legislating on the matter. The Bill protects equality under the law, since no natural or legal person is excluded from the right of offering these goods to the State under the conditions defined in the Bill and without more limitations than those established by the Law of State Contracts and Purchasing (T.U.O. by Supreme Decree No. 012-2001-PCM). The Bill does not introduce any discrimination whatever, since it only establishes *how* the goods have to be provided (which is a state power) and not *who* has to provide them (which would effectively be discriminatory, if restrictions based on national origin, race religion, ideology, sexual preference etc. were imposed). On the contrary, the Bill is decidedly antidiscriminatory. This is so because by defining with no room for doubt the conditions for the provision of software, it prevents state bodies from using software which has a license including discriminatory conditions. It should be obvious from the preceding two paragraphs that the Bill does not harm free private enterprise, since the latter can always choose under what conditions it will produce software; some of these will be acceptable to the State, and others will not be since they contradict the guarantee of the basic principles listed above. This free initiative is of course compatible with the freedom of industry and freedom of contract (in the limited form in which the State can exercise the latter). Any private subject can produce software under the conditions which the State requires, or can refrain from doing so. Nobody is forced to adopt a model of production, but if they wish to provide software to the State, they must provide the mechanisms which guarantee the basic principles, and which are those described in the Bill. By way of an example: nothing in the text of the Bill would prevent your company offering the State bodies an office "suite", under the conditions defined in the Bill and setting the price that you consider satisfactory. If you did not, it would not be due to restrictions imposed by the law, but to business decisions relative to the method of commercializing your products, decisions with which the State is not involved. To continue; you note that:" 2. The bill, by making the use of open source software compulsory, would establish discriminatory and non competitive practices in the contracting and purchasing by public bodies..." This statement is just a reiteration of the previous one, and so the response can be found above. However, let us concern ourselves for a moment with your comment regarding "non-competitive ... practices." Of course, in defining any kind of purchase, the buyer sets conditions which relate to the proposed use of the good or service. From the start, this excludes certain manufacturers from the possibility of competing, but does not exclude them "a priori", but rather based on a series of principles determined by the autonomous will of the purchaser, and so the process takes place in conformance with the law. And in the Bill it is established that *no one* is excluded from competing as far as he guarantees the fulfillment of the basic principles. Furthermore, the Bill *stimulates* competition, since it tends to generate a supply of software with better conditions of usability, and to better existing work, in a model of continuous improvement. On the other hand, the central aspect of competivity is the chance to provide better choices to the consumer. Now, it is impossible to ignore the fact that marketing does not play a neutral role when the product is offered on the market (since accepting the opposite would lead one to suppose that firms' expenses in marketing lack any sense), and that therefore a significant expense under this heading can influence the decisions of the purchaser. This influence of marketing is in large measure reduced by the bill that we are backing, since the choice within the framework proposed is based on the *technical merits* of the product and not on the effort put into commercialization by the producer; in this sense, competitiveness is increased, since the smallest software producer can compete on equal terms with the most powerful corporations. It is necessary to stress that there is no position more anti-competitive than that of the big software producers, which frequently abuse their dominant position, since in innumerable cases they propose as a solution to problems raised by users: "update your software to the new version" (at the user's expense, naturally); furthermore, it is common to find arbitrary cessation of technical help for products, which, in the provider's judgment alone, are "old"; and so, to receive any kind of technical assistance, the user finds himself forced to migrate to new versions (with non-trivial costs, especially as changes in hardware platform are often involved). And as the whole infrastructure is based on proprietary data formats, the user stays "trapped" in the need to continue using products from the same supplier, or to make the huge effort to change to another environment (probably also proprietary). You add: "3. So, by compelling the State to favor a business model based entirely on open source, the bill would only discourage the local and international manufacturing companies, which are the ones which really undertake important expenditures, create a significant number of direct and indirect jobs, as well as contributing to the GNP, as opposed to a model of open source software which tends to have an ever weaker economic impact, since it mainly creates jobs in the service sector." I do not agree with your statement. Partly because of what you yourself point out in paragraph 6 of your letter, regarding the relative weight of services in the context of software use. This contradiction alone would invalidate your position. The service model, adopted by a large number of companies in the software industry, is much larger in economic terms, and with a tendency to increase, than the licensing of programs. On the other hand, the private sector of the economy has the widest possible freedom to choose the economic model which best suits its interests, even if this freedom of choice is often obscured subliminally by the disproportionate expenditure on marketing by the producers of proprietary software. In addition, a reading of your opinion would lead to the conclusion that the State market is crucial and essential for the proprietary software industry, to such a point that the choice made by the State in this bill would completely eliminate the market for these firms. If that is true, we can deduce that the State must be subsidizing the proprietary software industry. In the unlikely event that this were true, the State would have the right to apply the subsidies in the area it considered of greatest social value; it is undeniable, in this improbable hypothesis, that if the State decided to subsidize software, it would have to do so choosing the free over the proprietary, considering its social effect and the rational use of taxpayers money. In respect of the jobs generated by proprietary software in countries like ours, these mainly concern technical tasks of little aggregate value; at the local level, the technicians who provide support for proprietary software produced by transnational companies do not have the possibility of fixing bugs, not necessarily for lack of technical capability or of talent, but because they do not have access to the source code to fix it. With free software one creates more technically qualified employment and a framework of free competence where success is only tied to the ability to offer good technical support and quality of service, one stimulates the market, and one increases the shared fund of knowledge, opening up alternatives to generate services of greater total value and a higher quality level, to the benefit of all involved: producers, service organizations, and consumers. It is a common phenomenon in developing countries that local software industries obtain the majority of their takings in the service sector, or in the creation of "ad hoc" software. Therefore, any negative impact that the application of the Bill might have in this sector will be more than compensated by a growth in demand for services (as long as these are carried out to high quality standards). If the transnational software companies decide not to compete under these new rules of the game, it is likely that they will undergo some decrease in takings in terms of payment for licenses; however, considering that these firms continue to allege that much of the software used by the State has been illegally copied, one can see that the impact will not be very serious. Certainly, in any case their fortune will be determined by market laws, changes in which cannot be avoided; many firms traditionally associated with proprietary software have already set out on the road (supported by copious expense) of providing services associated with free software, which shows that the models are not mutually exclusive. With this bill the State is deciding that it needs to preserve certain fundamental values. And it is deciding this based on its sovereign power, without affecting any of the constitutional guarantees. If these values could be guaranteed without having to choose a particular economic model, the effects of the law would be even more beneficial. In any case, it should be clear that the State does not choose an economic model; if it happens that there only exists one economic model capable of providing software which provides the basic guarantee of these principles, this is because of historical circumstances, not because of an arbitrary choice of a given model. Your letter continues: "4. The bill imposes the use of open source software without considering the dangers that this can bring from the point of view of security, guarantee, and possible violation of the intellectual property rights of third parties." Alluding in an abstract way to "the dangers this can bring", without specifically mentioning a single one of these supposed dangers, shows at the least some lack of knowledge of the topic. So, allow me to enlighten you on these points. On security: National security has already been mentioned in general terms in the initial discussion of the basic principles of the bill. In more specific terms, relative to the security of the software itself, it is well known that all software (whether proprietary or free) contains errors or "bugs" (in programmers' slang). But it is also well known that the bugs in free software are fewer, and are fixed much more quickly, than in proprietary software. It is not in vain that numerous public bodies responsible for the IT security of state systems in developed countries require the use of free software for the same conditions of security and efficiency. What is impossible to prove is that proprietary software is more secure than free, without the public and open inspection of the scientific community and users in general. This demonstration is impossible because the model of proprietary software itself prevents this analysis, so that any guarantee of security is based only on promises of good intentions (biased, by any reckoning) made by the producer itself, or its contractors. It should be remembered that in many cases, the licensing conditions include Non-Disclosure clauses which prevent the user from publicly revealing security flaws found in the licensed proprietary product. In respect of the guarantee: As you know perfectly well, or could find out by reading the "End User License Agreement" of the products you license, in the great majority of cases the guarantees are limited to replacement of the storage medium in case of defects, but in no case is compensation given for direct or indirect damages, loss of profits, etc... If as a result of a security bug in one of your products, not fixed in time by yourselves, an attacker managed to compromise crucial State systems, what guarantees, reparations and compensation would your company make in accordance with your licensing conditions? The guarantees of proprietary software, inasmuch as programs are delivered AS IS'', that is, in the state in which they are, with no additional responsibility of the provider in respect of function, in no way differ from those normal with free software. On Intellectual Property: Questions of intellectual property fall outside the scope of this bill, since they are covered by specific other laws. The model of free software in no way implies ignorance of these laws, and in fact the great majority of free software is covered by copyright. In reality, the inclusion of this question in your observations shows your confusion in respect of the legal framework in which free software is developed. The inclusion of the intellectual property of others in works claimed as one's own is not a practice that has been noted in the free software community; whereas, unfortunately, it has been in the area of proprietary software. As an example, the condemnation by the Commercial Court of Nanterre, France, on 27th September 2001 of Microsoft Corp. to a penalty of 3 million francs in damages and interest, for violation of intellectual property (piracy, to use the unfortunate term that your firm commonly uses in its publicity). You go on to say that: "The bill uses the concept of open source software incorrectly, since it does not necessarily imply that the software is free or of zero cost, and so arrives at mistaken conclusions regarding State savings, with no cost-benefit analysis to validate its position." This observation is wrong; in principle, freedom and lack of cost are orthogonal concepts: there is software which is proprietary and charged for (for example, MS Office), software which is proprietary and free of charge (MS Internet Explorer), software which is free and charged for (Red Hat, SuSE etc GNU/Linux distributions), software which is free and not charged for (Apache, Open Office, Mozilla), and even software which can be licensed in a range of combinations (MySQL). Certainly free software is not necessarily free of charge. And the text of the bill does not state that it has to be so, as you will have noted after reading it. The definitions included in the Bill state clearly *what* should be considered free software, at no point referring to freedom from charges. Although the possibility of savings in payments for proprietary software licenses are mentioned, the foundations of the bill clearly refer to the fundamental guarantees to be preserved and to the stimulus to local technological development. Given that a democratic State must support these principles, it has no other choice than to use software with publicly available source code, and to exchange information only in standard formats. If the State does not use software with these characteristics, it will be weakening basic republican principles. Luckily, free software also implies lower total costs; however, even given the hypothesis (easily disproved) that it was more expensive than proprietary software, the simple existence of an effective free software tool for a particular IT function would oblige the State to use it; not by command of this Bill, but because of the basic principles we enumerated at the start, and which arise from the very essence of the lawful democratic State. You continue: "6. It is wrong to think that Open Source Software is free of charge. Research by the Gartner Group (an important investigator of the technological market recognized at world level) has shown that the cost of purchase of software (operating system and applications) is only 8% of the total cost which firms and institutions take on for a rational and truly beneficial use of the technology. The other 92% consists of: installation costs, enabling, support, maintenance, administration, and down-time." This argument repeats that already given in paragraph 5 and partly contradicts paragraph 3. For the sake of brevity we refer to the comments on those paragraphs. However, allow me to point out that your conclusion is logically false: even if according to Gartner Group the cost of software is on average only 8% of the total cost of use, this does not in any way deny the existence of software which is free of charge, that is, with a licensing cost of zero. In addition, in this paragraph you correctly point out that the service components and losses due to down-time make up the largest part of the total cost of software use, which, as you will note, contradicts your statement regarding the small value of services suggested in paragraph 3. Now the use of free software contributes significantly to reduce the remaining life-cycle costs. This reduction in the costs of installation, support etc. can be noted in several areas: in the first place, the competitive service model of free software, support and maintenance for which can be freely contracted out to a range of suppliers competing on the grounds of quality and low cost. This is true for installation, enabling, and support, and in large part for maintenance. In the second place, due to the reproductive characteristics of the model, maintenance carried out for an application is easily replicable, without incurring large costs (that is, without paying more than once for the same thing) since modifications, if one wishes, can be incorporated in the common fund of knowledge. Thirdly, the huge costs caused by non-functioning software ("blue screens of death", malicious code such as virus, worms, and trojans, exceptions, general protection faults and other well-known problems) are reduced considerably by using more stable software; and it is well known that one of the most notable virtues of free software is its stability. You further state that: "7. One of the arguments behind the bill is the supposed freedom from costs of open-source software, compared with the costs of commercial software, without taking into account the fact that there exist types of volume licensing which can be highly advantageous for the State, as has happened in other countries." I have already pointed out that what is in question is not the cost of the software but the principles of freedom of information, accessibility, and security. These arguments have been covered extensively in the preceding paragraphs to which I would refer you. On the other hand, there certainly exist types of volume licensing (although unfortunately proprietary software does not satisfy the basic principles). But as you correctly pointed out in the immediately preceding paragraph of your letter, they only manage to reduce the impact of a component which makes up no more than 8% of the total. You continue: "8. In addition, the alternative adopted by the bill (I) is clearly more expensive, due to the high costs of software migration, and (II) puts at risk compatibility and interoperability of the IT platforms within the State, and between the State and the private sector, given the hundreds of versions of open source software on the market." Let us analyze your statement in two parts. Your first argument, that migration implies high costs, is in reality an argument in favor of the Bill. Because the more time goes by, the more difficult migration to another technology will become; and at the same time, the security risks associated with proprietary software will continue to increase. In this way, the use of proprietary systems and formats will make the State ever more dependent on specific suppliers. Once a policy of using free software has been established (which certainly, does imply some cost) then on the contrary migration from one system to another becomes very simple, since all data is stored in open formats. On the other hand, migration to an open software context implies no more costs than migration between two different proprietary software contexts, which invalidates your argument completely. The second argument refers to "problems in interoperability of the IT platforms within the State, and between the State and the private sector" This statement implies a certain lack of knowledge of the way in which free software is built, which does not maximize the dependence of the user on a particular platform, as normally happens in the realm of proprietary software. Even when there are multiple free software distributions, and numerous programs which can be used for the same function, interoperability is guaranteed as much by the use of standard formats, as required by the bill, as by the possibility of creating interoperable software given the availability of the source code. You then say that: "9. The majority of open source code does not offer adequate levels of service nor the guarantee from recognized manufacturers of high productivity on the part of the users, which has led various public organizations to retract their decision to go with an open source software solution and to use commercial software in its place." This observation is without foundation. In respect of the guarantee, your argument was rebutted in the response to paragraph 4. In respect of support services, it is possible to use free software without them (just as also happens with proprietary software), but anyone who does need them can obtain support separately, whether from local firms or from international corporations, again just as in the case of proprietary software. On the other hand, it would contribute greatly to our analysis if you could inform us about free software projects *established* in public bodies which have already been abandoned in favor of proprietary software. We know of a good number of cases where the opposite has taken place, but not know of any where what you describe has taken place. You continue by observing that: "10. The bill discourages the creativity of the Peruvian software industry, which invoices 40 million US$/year, exports 4 million US$ (10th in ranking among non-traditional exports, more than handicrafts) and is a source of highly qualified employment. With a law that encourages the use of open source, software programmers lose their intellectual property rights and their main source of payment." It is clear enough that nobody is forced to commercialize their code as free software. The only thing to take into account is that if it is not free software, it cannot be sold to the public sector. This is not in any case the main market for the national software industry. We covered some questions referring to the influence of the Bill on the generation of employment which would be both highly technically qualified and in better conditions for competition above, so it seems unnecessary to insist on this point. What follows in your statement is incorrect. On the one hand, no author of free software loses his intellectual property rights, unless he expressly wishes to place his work in the public domain. The free software movement has always been very respectful of intellectual property, and has generated widespread public recognition of its authors. Names like those of Richard Stallman, Linus Torvalds, Guido van Rossum, Larry Wall, Miguel de Icaza, Andrew Tridgell, Theo de Raadt, Andrea Arcangeli, Bruce Perens, Darren Reed, Alan Cox, Eric Raymond, and many others, are recognized world-wide for their contributions to the development of software that is used today by millions of people throughout the world. On the other hand, to say that the rewards for authors rights make up the main source of payment of Peruvian programmers is in any case a guess, in particular since there is no proof to this effect, nor a demonstration of how the use of free software by the State would influence these payments. You go on to say that: "11. Open source software, since it can be distributed without charge, does not allow the generation of income for its developers through exports. In this way, the multiplier effect of the sale of software to other countries is weakened, and so in turn is the growth of the industry, while Government rules ought on the contrary to stimulate local industry." This statement shows once again complete ignorance of the mechanisms of and market for free software. It tries to claim that the market of sale of non- exclusive rights for use (sale of licenses) is the only possible one for the software industry, when you yourself pointed out several paragraphs above that it is not even the most important one. The incentives that the bill offers for the growth of a supply of better qualified professionals, together with the increase in experience that working on a large scale with free software within the State will bring for Peruvian technicians, will place them in a highly competitive position to offer their services abroad. You then state that: "12. In the Forum, the use of open source software in education was discussed, without mentioning the complete collapse of this initiative in a country like Mexico, where precisely the State employees who founded the project now state that open source software did not make it possible to offer a learning experience to pupils in the schools, did not take into account the capability at a national level to give adequate support to the platform, and that the software did not and does not allow for the levels of platform integration that now exist in schools." In fact Mexico has gone into reverse with the Red Escolar (Schools Network) project. This is due precisely to the fact that the driving forces behind the Mexican project used license costs as their main argument, instead of the other reasons specified in our project, which are far more essential. Because of this conceptual mistake, and as a result of the lack of effective support from the SEP (Secretary of State for Public Education), the assumption was made that to implant free software in schools it would be enough to drop their software budget and send them a CD ROM with Gnu/Linux instead. Of course this failed, and it couldn't have been otherwise, just as school laboratories fail when they use proprietary software and have no budget for implementation and maintenance. That's exactly why our bill is not limited to making the use of free software mandatory, but recognizes the need to create a viable migration plan, in which the State undertakes the technical transition in an orderly way in order to then enjoy the advantages of free software. You end with a rhetorical question: "13. If open source software satisfies all the requirements of State bodies, why do you need a law to adopt it? Shouldn't it be the market which decides freely which products give most benefits or value?" We agree that in the private sector of the economy, it must be the market that decides which products to use, and no state interference is permissible there. However, in the case of the public sector, the reasoning is not the same: as we have already established, the state archives, handles, and transmits information which does not belong to it, but which is entrusted to it by citizens, who have no alternative under the rule of law. As a counterpart to this legal requirement, the State must take extreme measures to safeguard the integrity, confidentiality, and accessibility of this information. The use of proprietary software raises serious doubts as to whether these requirements can be fulfilled, lacks conclusive evidence in this respect, and so is not suitable for use in the public sector. The need for a law is based, firstly, on the realization of the fundamental principles listed above in the specific area of software; secondly, on the fact that the State is not an ideal homogeneous entity, but made up of multiple bodies with varying degrees of autonomy in decision making. Given that it is inappropriate to use proprietary software, the fact of establishing these rules in law will prevent the personal discretion of any state employee from putting at risk the information which belongs to citizens. And above all, because it constitutes an up-to-date reaffirmation in relation to the means of management and communication of information used today, it is based on the republican principle of openness to the public. In conformance with this universally accepted principle, the citizen has the right to know all information held by the State and not covered by well- founded declarations of secrecy based on law. Now, software deals with information and is itself information. Information in a special form, capable of being interpreted by a machine in order to execute actions, but crucial information all the same because the citizen has a legitimate right to know, for example, how his vote is computed or his taxes calculated. And for that he must have free access to the source code and be able to prove to his satisfaction the programs used for electoral computations or calculation of his taxes. I wish you the greatest respect, and would like to repeat that my office will always be open for you to expound your point of view to whatever level of detail you consider suitable. Cordially,
    DR. EDGAR DAVID VILLANUEVA NU EZ
    Congressman of the Republic of Per .

    22 December 2010

    Dirk Eddelbuettel: RcppExamples 0.1.2

    A new version of our RcppExamples, package is now on CRAN. RcppExamples contains a few illustrations of how to use Rcpp. It grew out of documentation for the classic API (now in its own package RcppClassic) and we added more functions documenting how to do the same with the new API we have been focusing on for the last year or so. One of the things I added in the last few days was the example below showing how to use Rcpp::List with lookups to replace use of the old and deprecated RcppParams. It also show how to return values to R rather easily <quote>
    #include <Rcpp.h>
    RcppExport SEXP newRcppParamsExample(SEXP params)  
        try                                         // or use BEGIN_RCPP macro
            Rcpp::List rparam(params);              // Get parameters in params.
            std::string method   = Rcpp::as<std::string>(rparam["method"]);
            double tolerance     = Rcpp::as<double>(rparam["tolerance"]);
            int    maxIter       = Rcpp::as<int>(rparam["maxIter"]);
            Rcpp::Date startDate = Rcpp::Date(Rcpp::as<int>(rparam["startDate"])); // ctor from int
            
            Rprintf("\nIn C++, seeing the following value\n");
            Rprintf("Method argument    : %s\n", method.c_str());
            Rprintf("Tolerance argument : %f\n", tolerance);
            Rprintf("MaxIter argument   : %d\n", maxIter);
            Rprintf("Start date argument: %04d-%02d-%02d\n", 
                    startDate.getYear(), startDate.getMonth(), startDate.getDay());
            return Rcpp::List::create(Rcpp::Named("method", method),
                                      Rcpp::Named("tolerance", tolerance),
                                      Rcpp::Named("maxIter", maxIter),
                                      Rcpp::Named("startDate", startDate),
                                      Rcpp::Named("params", params));  // or use rparam
          catch( std::exception &ex )               // or use END_RCPP macro
            forward_exception_to_r( ex );
          catch(...)   
            ::Rf_error( "c++ exception (unknown reason)" ); 
         
        return R_NilValue; // -Wall
     
    
    </quote> The package is work-in-progress and needs way more general usage examples for Rcpp and particularly the new API. But it's a start. A few more details on the page are on the RcppExamples page.

    20 December 2010

    Rapha&#235;l Hertzog: 5 reasons why Debian Unstable does not deserve its name

    Debian Unstable (also known as sid) is one of the 3 distributions that Debian provides (along with Stable and Testing). It s not conceived as a product for end-users, instead it s the place where contributors are uploading newer packages. Daily. Yes that means that Unstable is a quickly moving target and it s not for everybody. But you can use it and your computer won t explode. 1. It contains mainly stable versions of the software Yes, you read it right. Unstable is not full of development versions of the various software. It happens on some software but then it s usually a conscious decision of the maintainer who believes that this specific version is already better than the previous one. The packages in sid are supposed to migrate to testing, the place where the next Debian stable release is prepared. So maintainers are advised to only upload stuff that is of release quality, the rest should be uploaded to experimental instead. 2. It doesn t break badly every other day Breakages happen but they are not a big deal usually. It has been long time since I could not reboot my computer after an upgrade or since the graphical interface was no longer working. The kind of breakages that you have is that one software stops working, or triggers an annoying bug, or that a few packages are uninstallable. In most cases, you can save yourself by downgrading to the version available in Testing. Or by finding a work-around in the bug tracking system. Or by not upgrading because you have apt-listbugs installed and you have been warned about the problem. 3. It s the basis of other distributions If Debian Unstable was really so bad, it would not be a good basis to build a derivative distribution, isn t it? But Ubuntu and SiduxAptosid (to name only two) are based on Debian Sid. 4. It s not inherently less secure than Stable or Testing High impact security vulnerabilities will usually be quickly fixed in Stable and Unstable. The stable upload is done by the security team while the unstable one is made by the maintainer. Testing will usually get the fix through the package uploaded to Unstable, so testing users get security updates with a delay. For less serious vulnerabilities, it s entirely possible that stable does not get any update at all. In that case, unstable/testing users are better served since they will get the fix with the next upstream version anyway. Of course, it happens that maintainers are busy or that something falls through the cracks, but there are other people watching RC bugs who will fix this if the maintainer doesn t react at all. 5. I use it on my main computer And many other people do the same. And you can do the same if you meet the criteria below: If you feel you are not ready for the jump, click here to subscribe to this blog (or here via the RSS feed), I ll surely teach some of the required skills in future articles. PS: All that said, if you have a working sid installation, do not upgrade it just before an important presentation, or before a trip. It will always break at the most annoying time. Unless you like to live dangerously, of course.

    41 comments Liked this article? Click here. My blog is Flattr-enabled.

    16 December 2010

    Lars Wirzenius: Shadow of a bug

    I've recently spent five days debugging a problem in obnam, my backup program. It turned out to be a bug in my B-tree implementation, which I wrote for obnam. The process was pretty long, and it might be instructive to de-brief myself. The bug manifested itself when I ran a backup test that was larger than what I had ran before: one terabyte of live data. The symptom was a key lookup problem in a B-tree. Good: the problem was entirely deterministic, and easy to reproduce. Bad: it took hours to reproduce it. My first step was to fiddle with the obnam parameters to see if I could make it fail faster, but in the same way. I got the time down to half an hour. After this, I started fiddling with the code to see if I can figure out what happens, and perhaps find a quick fix to the bug. After some hours, I realized I was being stupid. I was making essentially random changes to the code, instead of hunting down the actual cause. I had no idea what was going wrong, so trying to fix it was an act of utter stupidty. So I went back to where I had started from. The next step was to run "obnam fsck" on the failing backup store. This did not find any problems. The fsck I've written is a bit simplistic, and merely checks that for every client in the backup store, every generation is found, and within every generation each file's metadata, and data chunks are found. I will improve fsck in the future, but right now it was not helpful. I did not have a tool to verify that the actual B-trees were OK. So I wrote one. It, too, is quite simplistic, but at least it proved that the key was still present in the on-disk version of the B-tree. At this point, I did a code review of the B-tree code. It had been a some months since I'd touched the code, and hence the review brought up a bunch of minor issues: outdated comments, badly formatted code, stupid variable names, etc. One or two buglets, too, but nothing relevant to the case of the missing key. At this point I made a mistake: I concluded that the error was not in the B-tree code, but the obnam code using the B-trees. I spent the next couple of days running the test case, adding more logging, and analyzing the results. Without my mistake, I would not have ignored indicators that would have led me faster into the depths of the B-tree code. I might have saved a day or two of the process. Eventually I narrowed down the problem to a single B-tree insertion call in the obnam code. The call inserted a new value for a given key into one tree, and the value in another tree changed as well. Quite mysterious. My B-trees are an implementation of the Rodeh B-trees. All updates are done using copy-on-write, and this allows efficient cloning of trees. However, as an optimization, a node that is used by only one tree at a time can be modified in-place. This speeds things up a lot when the same tree is updated many times. In obnam, each B-tree represents a backup generation. The specific bug I was hunting was that the key I use for storing the unique identifier for a generation changed in two trees at the same time. Now that I have actually found and fixed the problem, it is clear that I should have realized at once what was happening, but I didn't, so I spent another couple of days adding logging statements into the B-tree insertion code, and tracing where things went wrong. Since B-trees are updated quite heavily by obnam, the log files grew quite big, and the test runs grew quite long. The last run I did resulted in a 94 gigabyte log file, and lasted over 12 hours. less had trouble browsing the log file, probaby due to the rather long lines generated by dumps of the B-trees. I ended up splitting the large file into quite a number of small ones, using csplit. After some more analysis, I figured out the problem: the code that shadowed a B-tree node, i.e., implemented the copy-on-write modification, failed to update the reference counts of the children of a shadowed index node. The Rodeh B-trees use lazy reference counts: when an index node is shadowed, only the immediate children get reference count updates. This turns out to work quite well, and saves quite massive amounts of updates. Unfortunately, my code was too lazy, and did not update any reference counts. After I had come this far, it only took a couple of minutes to write a unit test to catch the problem, fix the code, run the unit tests successfully, and commit. Then I ran the big test case again, without the extra logging I had added, and the code worked fine. At least it worked fine for about 24 hours until it ate up all memory in the VM I was running it on, but that's a separate problem. What can I do to prevent this kind of bug happening in the future? Unit testing didn't catch it, and I have 100% statement coverage with unit tests (not counting 19 excluded statements). Code review by other programmers would surely help. I should perhaps attract others to the project. Please excuse the length of this blog post. It is a distillation of the about ten A4-pages' worth of notes I made during this debugging process. (Always make notes when debugging. Your brain can't remember all details.)

    3 December 2010

    Thijs Kinkhorst: Federated access to a wiki with simpleSAMLphp and Dokuwiki

    If you want to provide a wiki but want to leave the authentication to one or more external identity providers, like an identity federation, Dokuwiki and simpleSAMLphp are a good combination. However, the existing documentation is lagging behind on developments in these software packages (i.e. doesn't work anymore), so here's what worked for me. Ingredients:
    A Debian 5.0 Lenny system.
    Dokuwiki Debian Lenny package (0.0.20080505-4+lenny1).
    simpleSAMLphp Debian squeeze package (1.6.2-1).
    SSP is not available in Lenny yet but the package from Squeeze installs cleanly on Lenny.
    simpleSAMLdokuwiki integration package.
    Note that I'm linking to a bug report - you need the file version included in the bottom of that bug report, because the released versions are outdated.
    I assume you have read the Dokuwiki and simpleSAMLphp documentation for information on how to install and configure either one; this article purely focuses on the integration part; not on e.g. how to connect an IdP to simpleSAMLphp. I also provided a patch to the simplesamldokuwiki class cited above to enable the IdP to not pass a 'mail' attribute: see bug report.

    20 November 2010

    Petter Reinholdtsen: Lenny->Squeeze upgrades, apt vs aptitude with the Gnome and KDE desktop

    I'm still running upgrade testing of the Lenny Gnome and KDE Desktop, but have not had time to spend on reporting the status. Here is a short update based on a test I ran 20101118. I still do not know what a correct migration should look like, so I report any differences between apt and aptitude and hope someone else can see if anything should be changed. This is for Gnome: Installed using apt-get, missing with aptitude
    apache2.2-bin aptdaemon at-spi baobab binfmt-support browser-plugin-gnash cheese-common cli-common cpp-4.3 cups-pk-helper dmz-cursor-theme empathy empathy-common finger freedesktop-sound-theme freeglut3 gconf-defaults-service gdm-themes gedit-plugins geoclue geoclue-hostip geoclue-localnet geoclue-manual geoclue-yahoo gnash gnash-common gnome gnome-backgrounds gnome-cards-data gnome-codec-install gnome-core gnome-desktop-environment gnome-disk-utility gnome-screenshot gnome-search-tool gnome-session-canberra gnome-spell gnome-system-log gnome-themes-extras gnome-themes-more gnome-user-share gs-common gstreamer0.10-fluendo-mp3 gstreamer0.10-tools gtk2-engines gtk2-engines-pixbuf gtk2-engines-smooth hal-info hamster-applet libapache2-mod-dnssd libapr1 libaprutil1 libaprutil1-dbd-sqlite3 libaprutil1-ldap libart2.0-cil libatspi1.0-0 libboost-date-time1.42.0 libboost-python1.42.0 libboost-thread1.42.0 libchamplain-0.4-0 libchamplain-gtk-0.4-0 libcheese-gtk18 libclutter-gtk-0.10-0 libcryptui0 libcupsys2 libdiscid0 libeel2-data libelf1 libepc-1.0-2 libepc-common libepc-ui-1.0-2 libfreerdp-plugins-standard libfreerdp0 libgail-common libgconf2.0-cil libgdata-common libgdata7 libgdl-1-common libgdu-gtk0 libgee2 libgeoclue0 libgexiv2-0 libgif4 libglade2.0-cil libglib2.0-cil libgmime2.4-cil libgnome-vfs2.0-cil libgnome2.24-cil libgnomepanel2.24-cil libgnomeprint2.2-data libgnomeprintui2.2-common libgnomevfs2-bin libgpod-common libgpod4 libgtk2.0-cil libgtkglext1 libgtksourceview-common libgtksourceview2.0-common libmono-addins-gui0.2-cil libmono-addins0.2-cil libmono-cairo2.0-cil libmono-corlib2.0-cil libmono-i18n-west2.0-cil libmono-posix2.0-cil libmono-security2.0-cil libmono-sharpzip2.84-cil libmono-system2.0-cil libmtp8 libmusicbrainz3-6 libndesk-dbus-glib1.0-cil libndesk-dbus1.0-cil libopal3.6.8 libpolkit-gtk-1-0 libpt-1.10.10-plugins-alsa libpt-1.10.10-plugins-v4l libpt2.6.7 libpython2.6 librpm1 librpmio1 libsdl1.2debian libservlet2.4-java libsrtp0 libssh-4 libtelepathy-farsight0 libtelepathy-glib0 libtidy-0.99-0 libxalan2-java libxerces2-java media-player-info mesa-utils mono-2.0-gac mono-gac mono-runtime nautilus-sendto nautilus-sendto-empathy openoffice.org-writer2latex openssl-blacklist p7zip p7zip-full pkg-config python-4suite-xml python-aptdaemon python-aptdaemon-gtk python-axiom python-beautifulsoup python-bugbuddy python-clientform python-coherence python-configobj python-crypto python-cupshelpers python-cupsutils python-eggtrayicon python-elementtree python-epsilon python-evolution python-feedparser python-gdata python-gdbm python-gst0.10 python-gtkglext1 python-gtkmozembed python-gtksourceview2 python-httplib2 python-louie python-mako python-markupsafe python-mechanize python-nevow python-notify python-opengl python-openssl python-pam python-pkg-resources python-pyasn1 python-pysqlite2 python-rdflib python-serial python-tagpy python-twisted-bin python-twisted-conch python-twisted-core python-twisted-web python-utidylib python-webkit python-xdg python-zope.interface remmina remmina-plugin-data remmina-plugin-rdp remmina-plugin-vnc rhythmbox-plugin-cdrecorder rhythmbox-plugins rpm-common rpm2cpio seahorse-plugins shotwell software-center svgalibg1 system-config-printer-udev telepathy-gabble telepathy-mission-control-5 telepathy-salut tomboy totem totem-coherence totem-mozilla totem-plugins transmission-common xdg-user-dirs xdg-user-dirs-gtk xserver-xephyr zip
    Installed using apt-get, removed with aptitude
    arj bluez-utils cheese dhcdbd djvulibre-desktop ekiga eog epiphany-extensions epiphany-gecko evolution-exchange fast-user-switch-applet file-roller gcalctool gconf-editor gdm gedit gedit-common gnome-app-install gnome-games gnome-games-data gnome-nettool gnome-system-tools gnome-themes gnome-utils gnome-vfs-obexftp gnome-volume-manager gnuchess gucharmap guile-1.8-libs hal libavahi-compat-libdnssd1 libavahi-core5 libavahi-ui0 libbind9-50 libbluetooth2 libcamel1.2-11 libcdio7 libcucul0 libcurl3 libdirectfb-1.0-0 libdmx1 libdvdread3 libedata-cal1.2-6 libedataserver1.2-9 libeel2-2.20 libepc-1.0-1 libepc-ui-1.0-1 libexchange-storage1.2-3 libfaad0 libgadu3 libgalago3 libgd2-noxpm libgda3-3 libgda3-common libggz2 libggzcore9 libggzmod4 libgksu1.2-0 libgksuui1.0-1 libgmyth0 libgnome-desktop-2 libgnome-pilot2 libgnomecups1.0-1 libgnomeprint2.2-0 libgnomeprintui2.2-0 libgpod3 libgraphviz4 libgtk-vnc-1.0-0 libgtkhtml2-0 libgtksourceview1.0-0 libgtksourceview2.0-0 libgucharmap6 libhesiod0 libicu38 libisccc50 libisccfg50 libiw29 libjaxp1.3-java-gcj libkpathsea4 liblircclient0 libltdl3 liblwres50 libmagick++10 libmagick10 libmalaga7 libmozjs1d libmpfr1ldbl libmtp7 libmysqlclient15off libnautilus-burn4 libneon27 libnm-glib0 libnm-util0 libopal-2.2 libosp5 libparted1.8-10 libpisock9 libpisync1 libpoppler-glib3 libpoppler3 libpt-1.10.10 libraw1394-8 libsdl1.2debian-alsa libsensors3 libsexy2 libsmbios2 libsoup2.2-8 libspeexdsp1 libssh2-1 libsuitesparse-3.1.0 libsvga1 libswfdec-0.6-90 libtalloc1 libtotem-plparser10 libtrackerclient0 libvoikko1 libxalan2-java-gcj libxerces2-java-gcj libxklavier12 libxtrap6 libxxf86misc1 libzephyr3 mysql-common rhythmbox seahorse sound-juicer swfdec-gnome system-config-printer totem-common totem-gstreamer transmission-gtk vinagre vino w3c-dtd-xhtml wodim
    Installed using aptitude, missing with apt-get
    gstreamer0.10-gnomevfs
    Installed using aptitude, removed with apt-get
    [nothing]
    This is for KDE: Installed using apt-get, missing with aptitude
    autopoint bomber bovo cantor cantor-backend-kalgebra cpp-4.3 dcoprss edict espeak espeak-data eyesapplet fifteenapplet finger gettext ghostscript-x git gnome-audio gnugo granatier gs-common gstreamer0.10-pulseaudio indi kaddressbook-plugins kalgebra kalzium-data kanjidic kapman kate-plugins kblocks kbreakout kbstate kde-icons-mono kdeaccessibility kdeaddons-kfile-plugins kdeadmin-kfile-plugins kdeartwork-misc kdeartwork-theme-window kdeedu kdeedu-data kdeedu-kvtml-data kdegames kdegames-card-data kdegames-mahjongg-data kdegraphics-kfile-plugins kdelirc kdemultimedia-kfile-plugins kdenetwork-kfile-plugins kdepim-kfile-plugins kdepim-kio-plugins kdessh kdetoys kdewebdev kdiamond kdnssd kfilereplace kfourinline kgeography-data kigo killbots kiriki klettres-data kmoon kmrml knewsticker-scripts kollision kpf krosspython ksirk ksmserver ksquares kstars-data ksudoku kubrick kweather libasound2-plugins libboost-python1.42.0 libcfitsio3 libconvert-binhex-perl libcrypt-ssleay-perl libdb4.6++ libdjvulibre-text libdotconf1.0 liberror-perl libespeak1 libfinance-quote-perl libgail-common libgsl0ldbl libhtml-parser-perl libhtml-tableextract-perl libhtml-tagset-perl libhtml-tree-perl libio-stringy-perl libkdeedu4 libkdegames5 libkiten4 libkpathsea5 libkrossui4 libmailtools-perl libmime-tools-perl libnews-nntpclient-perl libopenbabel3 libportaudio2 libpulse-browse0 libservlet2.4-java libspeechd2 libtiff-tools libtimedate-perl libunistring0 liburi-perl libwww-perl libxalan2-java libxerces2-java lirc luatex marble networkstatus noatun-plugins openoffice.org-writer2latex palapeli palapeli-data parley parley-data poster psutils pulseaudio pulseaudio-esound-compat pulseaudio-module-x11 pulseaudio-utils quanta-data rocs rsync speech-dispatcher step svgalibg1 texlive-binaries texlive-luatex ttf-sazanami-gothic
    Installed using apt-get, removed with aptitude
    amor artsbuilder atlantik atlantikdesigner blinken bluez-utils cvs dhcdbd djvulibre-desktop imlib-base imlib11 kalzium kanagram kandy kasteroids katomic kbackgammon kbattleship kblackbox kbounce kbruch kcron kdat kdemultimedia-kappfinder-data kdeprint kdict kdvi kedit keduca kenolaba kfax kfaxview kfouleggs kgeography kghostview kgoldrunner khangman khexedit kiconedit kig kimagemapeditor kitchensync kiten kjumpingcube klatin klettres klickety klines klinkstatus kmag kmahjongg kmailcvt kmenuedit kmid kmilo kmines kmousetool kmouth kmplot knetwalk kodo kolf kommander konquest kooka kpager kpat kpdf kpercentage kpilot kpoker kpovmodeler krec kregexpeditor kreversi ksame ksayit kshisen ksig ksim ksirc ksirtet ksmiletris ksnake ksokoban kspaceduel kstars ksvg ksysv kteatime ktip ktnef ktouch ktron kttsd ktuberling kturtle ktux kuickshow kverbos kview kviewshell kvoctrain kwifimanager kwin kwin4 kwordquiz kworldclock kxsldbg libakode2 libarts1-akode libarts1-audiofile libarts1-mpeglib libarts1-xine libavahi-compat-libdnssd1 libavahi-core5 libavc1394-0 libbind9-50 libbluetooth2 libboost-python1.34.1 libcucul0 libcurl3 libcvsservice0 libdirectfb-1.0-0 libdjvulibre21 libdvdread3 libfaad0 libfreebob0 libgd2-noxpm libgraphviz4 libgsmme1c2a libgtkhtml2-0 libicu38 libiec61883-0 libindex0 libisccc50 libisccfg50 libiw29 libjaxp1.3-java-gcj libk3b3 libkcal2b libkcddb1 libkdeedu3 libkdegames1 libkdepim1a libkgantt0 libkleopatra1 libkmime2 libkpathsea4 libkpimexchange1 libkpimidentities1 libkscan1 libksieve0 libktnef1 liblockdev1 libltdl3 liblwres50 libmagick10 libmimelib1c2a libmodplug0c2 libmozjs1d libmpcdec3 libmpfr1ldbl libneon27 libnm-util0 libopensync0 libpisock9 libpoppler-glib3 libpoppler-qt2 libpoppler3 libraw1394-8 librss1 libsensors3 libsmbios2 libssh2-1 libsuitesparse-3.1.0 libswfdec-0.6-90 libtalloc1 libxalan2-java-gcj libxerces2-java-gcj libxtrap6 lskat mpeglib network-manager-kde noatun pmount tex-common texlive-base texlive-common texlive-doc-base texlive-fonts-recommended tidy ttf-dustin ttf-kochi-gothic ttf-sjfonts
    Installed using aptitude, missing with apt-get
    dolphin kde-core kde-plasma-desktop kde-standard kde-window-manager kdeartwork kdebase kdebase-apps kdebase-workspace kdebase-workspace-bin kdebase-workspace-data kdeutils kscreensaver kscreensaver-xsavers libgle3 libkonq5 libkonq5-templates libnetpbm10 netpbm plasma-widget-folderview plasma-widget-networkmanagement xscreensaver-data-extra xscreensaver-gl xscreensaver-gl-extra xscreensaver-screensaver-bsod
    Installed using aptitude, removed with apt-get
    kdebase-bin konq-plugins konqueror

    18 October 2010

    Francois Marier: Manipulating debconf settings on the command line

    It's not very easy to find information on how to adjust debconf settings after a package has been installed and configured. Most of the information out there is for Debian developers wanting to add support for debconf in their maintainer scripts.

    I ran into the problem of being unable to change a package's configuration options through dpkg-reconfigure and I found the following commands to do it manually:

    debconf-show packagename

    to show the list of debconf values that a package has stored,

    echo "get packagename/pgsql/app-pass" debconf-communicate

    to query the current value of an option in the debconf database, and

    echo "set packagename/pgsql/app-pass password1" debconf-communicate

    to change that value.

    I'm not convinced that this is the easiest way for system administrators to manually lookup and modify debconf options, but that's the best I could find at the time.

    15 October 2010

    Enrico Zini: Award winning code

    Award winning code Me and Yuwei had a fun day at hhhmcr (#hhhmcr) and even managed to put together a prototype that won the first prize \o/ We played with the gmp24 dataset kindly extracted from Twitter by Michael Brunton-Spall of the Guardian into a convenient JSON dataset. The idea was to find ways of making it easier to look at the data and making sense of it. This is the story of what we did, including the code we wrote. The original dataset has several JSON files, so the first task was to put them all together:
    #!/usr/bin/python
    # Merge the JSON data
    # (C) 2010 Enrico Zini <enrico@enricozini.org>
    # License: WTFPL version 2 (http://sam.zoy.org/wtfpl/)
    import simplejson
    import os
    res = []
    for f in os.listdir("."):
        if not f.startswith("gmp24"): continue
        data = open(f).read().strip()
        if data == "[]": continue
        parsed = simplejson.loads(data)
        res.extend(parsed)
    print simplejson.dumps(res)
    
    The results however were not ordered by date, as GMP had to use several accounts to twit because Twitter was putting Greather Manchester Police into jail for generating too much traffic. There would be quite a bit to write about that, but let's stick to our work. Here is code to sort the JSON data by time:
    #!/usr/bin/python
    # Sort the JSON data
    # (C) 2010 Enrico Zini <enrico@enricozini.org>
    # License: WTFPL version 2 (http://sam.zoy.org/wtfpl/)
    import simplejson
    import sys
    import datetime as dt
    all_recs = simplejson.load(sys.stdin)
    all_recs.sort(key=lambda x: dt.datetime.strptime(x["created_at"], "%a %b %d %H:%M:%S +0000 %Y"))
    simplejson.dump(all_recs, sys.stdout)
    
    I then wanted to play with Tf-idf for extracting the most important words of every tweet:
    #!/usr/bin/python
    # tfifd - Annotate JSON elements with Tf-idf extracted keywords
    #
    # Copyright (C) 2010  Enrico Zini <enrico@enricozini.org>
    #
    # 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/>.
    import sys, math
    import simplejson
    import re
    # Read all the twits
    records = simplejson.load(sys.stdin)
    # All the twits by ID
    byid = dict(((x["id"], x) for x in records))
    # Stopwords we ignore
    stopwords = set(["by", "it", "and", "of", "in", "a", "to"])
    # Tokenising engine
    re_num = re.compile(r"^\d+$")
    re_word = re.compile(r"(\w+)")
    def tokenise(tweet):
        "Extract tokens from a tweet"
        for tok in tweet["text"].split():
            tok = tok.strip().lower()
            if re_num.match(tok): continue
            mo = re_word.match(tok)
            if not mo: continue
            if mo.group(1) in stopwords: continue
            yield mo.group(1)
    # Extract tokens from tweets
    tokenised = dict(((x["id"], list(tokenise(x))) for x in records))
    # Aggregate token counts
    aggregated =  
    for d in byid.iterkeys():
        for t in tokenised[d]:
            if t in aggregated:
                aggregated[t] += 1
            else:
                aggregated[t] = 1
    def tfidf(doc, tok):
        "Compute TFIDF score of a token in a document"
        return doc.count(tok) * math.log(float(len(byid)) / aggregated[tok])
    # Annotate tweets with keywords
    res = []
    for name, tweet in byid.iteritems():
        doc = tokenised[name]
        keywords = sorted(set(doc), key=lambda tok: tfidf(doc, tok), reverse=True)[:5]
        tweet["keywords"] = keywords
        res.append(tweet)
    simplejson.dump(res, sys.stdout)
    
    I thought this was producing a nice summary of every tweet but nobody was particularly interested, so we moved on to adding categories to tweet. Thanks to Yuwei who put together some useful keyword sets, we managed to annotate each tweet with a place name (i.e. "Stockport"), a social place name (i.e. "pub", "bank") and a social category (i.e. "man", "woman", "landlord"...) The code is simple; the biggest work in it was the dictionary of keywords:
    #!/usr/bin/python
    # categorise - Annotate JSON elements with categories
    #
    # Copyright (C) 2010  Enrico Zini <enrico@enricozini.org>
    # Copyright (C) 2010  Yuwei Lin <yuwei@ylin.org>
    #
    # 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/>.
    import sys, math
    import simplejson
    import re
    # Electoral wards from http://en.wikipedia.org/wiki/List_of_electoral_wards_in_Greater_Manchester
    placenames = ["Altrincham", "Sale West",
    "Altrincham", "Ashton upon Mersey", "Bowdon", "Broadheath", "Hale Barns", "Hale Central", "St Mary", "Timperley", "Village",
    "Ashton-under-Lyne",
    "Ashton Hurst", "Ashton St Michael", "Ashton Waterloo", "Droylsden East", "Droylsden West", "Failsworth East", "Failsworth West", "St Peter",
    "Blackley", "Broughton",
    "Broughton", "Charlestown", "Cheetham", "Crumpsall", "Harpurhey", "Higher Blackley", "Kersal",
    "Bolton North East",
    "Astley Bridge", "Bradshaw", "Breightmet", "Bromley Cross", "Crompton", "Halliwell", "Tonge with the Haulgh",
    "Bolton South East",
    "Farnworth", "Great Lever", "Harper Green", "Hulton", "Kearsley", "Little Lever", "Darcy Lever", "Rumworth",
    "Bolton West",
    "Atherton", "Heaton", "Lostock", "Horwich", "Blackrod", "Horwich North East", "Smithills", "Westhoughton North", "Chew Moor", "Westhoughton South",
    "Bury North",
    "Church", "East", "Elton", "Moorside", "North Manor", "Ramsbottom", "Redvales", "Tottington",
    "Bury South",
    "Besses", "Holyrood", "Pilkington Park", "Radcliffe East", "Radcliffe North", "Radcliffe West", "St Mary", "Sedgley", "Unsworth",
    "Cheadle",
    "Bramhall North", "Bramhall South", "Cheadle", "Gatley", "Cheadle Hulme North", "Cheadle Hulme South", "Heald Green", "Stepping Hill",
    "Denton", "Reddish",
    "Audenshaw", "Denton North East", "Denton South", "Denton West", "Dukinfield", "Reddish North", "Reddish South",
    "Hazel Grove",
    "Bredbury", "Woodley", "Bredbury Green", "Romiley", "Hazel Grove", "Marple North", "Marple South", "Offerton",
    "Heywood", "Middleton",
    "Bamford", "Castleton", "East Middleton", "Hopwood Hall", "Norden", "North Heywood", "North Middleton", "South Middleton", "West Heywood", "West Middleton",
    "Leigh",
    "Astley Mosley Common", "Atherleigh", "Golborne", "Lowton West", "Leigh East", "Leigh South", "Leigh West", "Lowton East", "Tyldesley",
    "Makerfield",
    "Abram", "Ashton", "Bryn", "Hindley", "Hindley Green", "Orrell", "Winstanley", "Worsley Mesnes",
    "Manchester Central",
    "Ancoats", "Clayton", "Ardwick", "Bradford", "City Centre", "Hulme", "Miles Platting", "Newton Heath", "Moss Side", "Moston",
    "Manchester", "Gorton",
    "Fallowfield", "Gorton North", "Gorton South", "Levenshulme", "Longsight", "Rusholme", "Whalley Range",
    "Manchester", "Withington",
    "Burnage", "Chorlton", "Chorlton Park", "Didsbury East", "Didsbury West", "Old Moat", "Withington",
    "Oldham East", "Saddleworth",
    "Alexandra", "Crompton", "Saddleworth North", "Saddleworth South", "Saddleworth West", "Lees", "St James", "St Mary", "Shaw", "Waterhead",
    "Oldham West", "Royton",
    "Chadderton Central", "Chadderton North", "Chadderton South", "Coldhurst", "Hollinwood", "Medlock Vale", "Royton North", "Royton South", "Werneth",
    "Rochdale",
    "Balderstone", "Kirkholt", "Central Rochdale", "Healey", "Kingsway", "Littleborough Lakeside", "Milkstone", "Deeplish", "Milnrow", "Newhey", "Smallbridge", "Firgrove", "Spotland", "Falinge", "Wardle", "West Littleborough",
    "Salford", "Eccles",
    "Claremont", "Eccles", "Irwell Riverside", "Langworthy", "Ordsall", "Pendlebury", "Swinton North", "Swinton South", "Weaste", "Seedley",
    "Stalybridge", "Hyde",
    "Dukinfield Stalybridge", "Hyde Godley", "Hyde Newton", "Hyde Werneth", "Longdendale", "Mossley", "Stalybridge North", "Stalybridge South",
    "Stockport",
    "Brinnington", "Central", "Davenport", "Cale Green", "Edgeley", "Cheadle Heath", "Heatons North", "Heatons South", "Manor",
    "Stretford", "Urmston",
    "Bucklow-St Martins", "Clifford", "Davyhulme East", "Davyhulme West", "Flixton", "Gorse Hill", "Longford", "Stretford", "Urmston",
    "Wigan",
    "Aspull New Springs Whelley", "Douglas", "Ince", "Pemberton", "Shevington with Lower Ground", "Standish with Langtree", "Wigan Central", "Wigan West",
    "Worsley", "Eccles South",
    "Barton", "Boothstown", "Ellenbrook", "Cadishead", "Irlam", "Little Hulton", "Walkden North", "Walkden South", "Winton", "Worsley",
    "Wythenshawe", "Sale East",
    "Baguley", "Brooklands", "Northenden", "Priory", "Sale Moor", "Sharston", "Woodhouse Park"]
    # Manual coding from Yuwei
    placenames.extend(["City centre", "Tameside", "Oldham", "Bury", "Bolton",
    "Trafford", "Pendleton", "New Moston", "Denton", "Eccles", "Leigh", "Benchill",
    "Prestwich", "Sale", "Kearsley", ])
    placenames.extend(["Trafford", "Bolton", "Stockport", "Levenshulme", "Gorton",
    "Tameside", "Blackley", "City centre", "Airport", "South Manchester",
    "Rochdale", "Chorlton", "Uppermill", "Castleton", "Stalybridge", "Ashton",
    "Chadderton", "Bury", "Ancoats", "Whalley Range", "West Yorkshire",
    "Fallowfield", "New Moston", "Denton", "Stretford", "Eccles", "Pendleton",
    "Leigh", "Altrincham", "Sale", "Prestwich", "Kearsley", "Hulme", "Withington",
    "Moss Side", "Milnrow", "outskirt of Manchester City Centre", "Newton Heath",
    "Wythenshawe", "Mancunian Way", "M60", "A6", "Droylesden", "M56", "Timperley",
    "Higher Ince", "Clayton", "Higher Blackley", "Lowton", "Droylsden",
    "Partington", "Cheetham Hill", "Benchill", "Longsight", "Didsbury",
    "Westhoughton"])
    # Social categories from Yuwei
    soccat = ["man", "woman", "men", "women", "youth", "teenager", "elderly",
    "patient", "taxi driver", "neighbour", "male", "tenant", "landlord", "child",
    "children", "immigrant", "female", "workmen", "boy", "girl", "foster parents",
    "next of kin"]
    for i in range(100):
        soccat.append("%d-year-old" % i)
        soccat.append("%d-years-old" % i)
    # Types of social locations from Yuwei
    socloc = ["car park", "park", "pub", "club", "shop", "premises", "bus stop",
    "property", "credit card", "supermarket", "garden", "phone box", "theatre",
    "toilet", "building site", "Crown court", "hard shoulder", "telephone kiosk",
    "hotel", "restaurant", "cafe", "petrol station", "bank", "school",
    "university"]
    extras =   "placename": placenames, "soccat": soccat, "socloc": socloc  
    # Normalise keyword lists
    for k, v in extras.iteritems():
        # Remove duplicates
        v = list(set(v))
        # Sort by length
        v.sort(key=lambda x:len(x), reverse=True)
    # Add keywords
    def add_categories(tweet):
        text = tweet["text"].lower()
        for field, categories in extras.iteritems():
            for cat in categories:
                if cat.lower() in text:
                    tweet[field] = cat
                    break
        return tweet
    # Read all the twits
    records = (add_categories(x) for x in simplejson.load(sys.stdin))
    simplejson.dump(list(records), sys.stdout)
    
    All these scripts form a nice processing chain: each script takes a list of JSON records, adds some bit and passes it on. In order to see what we have so far, here is a simple script to convert the JSON twits to CSV so they can be viewed in a spreadsheet:
    #!/usr/bin/python
    # Convert the JSON twits to CSV
    # (C) 2010 Enrico Zini <enrico@enricozini.org>
    # License: WTFPL version 2 (http://sam.zoy.org/wtfpl/)
    import simplejson
    import sys
    import csv
    rows = ["id", "created_at", "text", "keywords", "placename"]
    writer = csv.writer(sys.stdout)
    for rec in simplejson.load(sys.stdin):
        rec["keywords"] = " ".join(rec["keywords"])
        rec["placename"] = rec.get("placename", "")
        writer.writerow([rec[row] for row in rows])
    
    At this point we were coming up with lots of questions: "were there more reports on women or men?", "which place had most incidents?", "what were the incidents involving animals?"... Time to bring Xapian into play. This script reads all the JSON tweets and builds a Xapian index with them:
    #!/usr/bin/python
    # toxapian - Index JSON tweets in Xapian
    #
    # Copyright (C) 2010  Enrico Zini <enrico@enricozini.org>
    #
    # 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/>.
    import simplejson
    import sys
    import os, os.path
    import xapian
    DBNAME = sys.argv[1]
    db = xapian.WritableDatabase(DBNAME, xapian.DB_CREATE_OR_OPEN)
    stemmer = xapian.Stem("english")
    indexer = xapian.TermGenerator()
    indexer.set_stemmer(stemmer)
    indexer.set_database(db)
    data = simplejson.load(sys.stdin)
    for rec in data:
        doc = xapian.Document()
        doc.set_data(str(rec["id"]))
        indexer.set_document(doc)
        indexer.index_text_without_positions(rec["text"])
        # Index categories as categories
        if "placename" in rec:
            doc.add_boolean_term("XP" + rec["placename"].lower())
        if "soccat" in rec:
            doc.add_boolean_term("XS" + rec["soccat"].lower())
        if "socloc" in rec:
            doc.add_boolean_term("XL" + rec["socloc"].lower())
        db.add_document(doc)
    db.flush()
    # Also save the whole dataset so we know where to find it later if we want to
    # show the details of an entry
    simplejson.dump(data, open(os.path.join(DBNAME, "all.json"), "w"))
    
    And this is a simple command line tool to query to the database:
    #!/usr/bin/python
    # xgrep - Command line tool to query the GMP24 tweet Xapian database
    #
    # Copyright (C) 2010  Enrico Zini <enrico@enricozini.org>
    #
    # 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/>.
    import simplejson
    import sys
    import os, os.path
    import xapian
    DBNAME = sys.argv[1]
    db = xapian.Database(DBNAME)
    stem = xapian.Stem("english")
    qp = xapian.QueryParser()
    qp.set_default_op(xapian.Query.OP_AND)
    qp.set_database(db)
    qp.set_stemmer(stem)
    qp.set_stemming_strategy(xapian.QueryParser.STEM_SOME)
    qp.add_boolean_prefix("place", "XP")
    qp.add_boolean_prefix("soc", "XS")
    qp.add_boolean_prefix("loc", "XL")
    query = qp.parse_query(sys.argv[2],
        xapian.QueryParser.FLAG_BOOLEAN  
        xapian.QueryParser.FLAG_LOVEHATE  
        xapian.QueryParser.FLAG_BOOLEAN_ANY_CASE  
        xapian.QueryParser.FLAG_WILDCARD  
        xapian.QueryParser.FLAG_PURE_NOT  
        xapian.QueryParser.FLAG_SPELLING_CORRECTION  
        xapian.QueryParser.FLAG_AUTO_SYNONYMS)
    enquire = xapian.Enquire(db)
    enquire.set_query(query)
    count = 40
    matches = enquire.get_mset(0, count)
    estimated = matches.get_matches_estimated()
    print "%d/%d results" % (matches.size(), estimated)
    data = dict((str(x["id"]), x) for x in simplejson.load(open(os.path.join(DBNAME, "all.json"))))
    for m in matches:
        rec = data[m.document.get_data()]
        print rec["text"]
    print "%d/%d results" % (matches.size(), matches.get_matches_estimated())
    total = db.get_doccount()
    estimated = matches.get_matches_estimated()
    print "%d results over %d documents, %d%%" % (estimated, total, estimated * 100 / total)
    
    Neat! Now that we have a proper index that supports all sort of cool things, like stemming, tag clouds, full text search with complex queries, lookup of similar documents, suggest keywords and so on, it was just fair to put together a web service to share it with other people at the event. It helped that I had already written similar code for apt-xapian-index and dde before. Here is the server, quickly built on bottle. The very last line starts the server and it is where you can configure the listening interface and port.
    #!/usr/bin/python
    # xserve - Make the GMP24 tweet Xapian database available on the web
    #
    # Copyright (C) 2010  Enrico Zini <enrico@enricozini.org>
    #
    # 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/>.
    import bottle
    from bottle import route, post
    from cStringIO import StringIO
    import cPickle as pickle
    import simplejson
    import sys
    import os, os.path
    import xapian
    import urllib
    import math
    bottle.debug(True)
    DBNAME = sys.argv[1]
    QUERYLOG = os.path.join(DBNAME, "queries.txt")
    data = dict((str(x["id"]), x) for x in simplejson.load(open(os.path.join(DBNAME, "all.json"))))
    prefixes =   "place": "XP", "soc": "XS", "loc": "XL"  
    prefix_desc =   "place": "Place name", "soc": "Social category", "loc": "Social location"  
    db = xapian.Database(DBNAME)
    stem = xapian.Stem("english")
    qp = xapian.QueryParser()
    qp.set_default_op(xapian.Query.OP_AND)
    qp.set_database(db)
    qp.set_stemmer(stem)
    qp.set_stemming_strategy(xapian.QueryParser.STEM_SOME)
    for k, v in prefixes.iteritems():
        qp.add_boolean_prefix(k, v)
    def make_query(qstring):
        return qp.parse_query(qstring,
            xapian.QueryParser.FLAG_BOOLEAN  
            xapian.QueryParser.FLAG_LOVEHATE  
            xapian.QueryParser.FLAG_BOOLEAN_ANY_CASE  
            xapian.QueryParser.FLAG_WILDCARD  
            xapian.QueryParser.FLAG_PURE_NOT  
            xapian.QueryParser.FLAG_SPELLING_CORRECTION  
            xapian.QueryParser.FLAG_AUTO_SYNONYMS)
    @route("/")
    def index():
        query = urllib.unquote_plus(bottle.request.GET.get("q", ""))
        out = StringIO()
        print >>out, '''
    <html>
    <head>
    <title>Query</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript">
    $(function() 
        $("#queryfield")[0].focus()
     )
    </script>
    </head>
    <body>
    <h1>Search</h1>
    <form method="POST" action="/query">
    Keywords: <input type="text" name="query" value="%s" id="queryfield">
    <input type="submit">
    <a href="http://xapian.org/docs/queryparser.html">Help</a>
    </form>''' % query
        print >>out, '''
    <p>Example: "car place:wigan"</p>
    
    <p>Available prefixes:</p>
    
    <ul>
    '''
        for pfx in prefixes.keys():
            print >>out, "<li><a href='/catinfo/%s'>%s - %s</a></li>" % (pfx, pfx, prefix_desc[pfx])
        print >>out, '''
    </ul>
    '''
        oldqueries = []
        if os.path.exists(QUERYLOG):
            total = db.get_doccount()
            fd = open(QUERYLOG, "r")
            while True:
                try:
                    q = pickle.load(fd)
                except EOFError:
                    break
                oldqueries.append(q)
            fd.close()
            def print_query(q):
                count = q["count"]
                print >>out, "<li><a href='/query?query=%s'>%s (%d/%d %.2f%%)</a></li>" % (urllib.quote_plus(q["q"]), q["q"], count, total, count * 100.0 / total)
            print >>out, "<p>Last 10 queries:</p><ul>"
            for q in oldqueries[:-10:-1]:
                print_query(q)
            print >>out, "</ul>"
            # Remove duplicates
            oldqueries = dict(((x["q"], x) for x in oldqueries)).values()
            print >>out, "<table>"
            print >>out, "<tr><th>10 queries with most results</th><th>10 queries with least results</th></tr>"
            print >>out, "<tr><td>"
            print >>out, "<ul>"
            oldqueries.sort(key=lambda x:x["count"], reverse=True)
            for q in oldqueries[:10]:
                print_query(q)
            print >>out, "</ul>"
            print >>out, "</td><td>"
            print >>out, "<ul>"
            nonempty = [x for x in oldqueries if x["count"] > 0]
            nonempty.sort(key=lambda x:x["count"])
            for q in nonempty[:10]:
                print_query(q)
            print >>out, "</ul>"
            print >>out, "</td></tr>"
            print >>out, "</table>"
        print >>out, '''
    </body>
    </html>'''
        return out.getvalue()
    @route("/query")
    @route("/query/")
    @post("/query")
    @post("/query/")
    def query():
        query = bottle.request.POST.get("query", bottle.request.GET.get("query", ""))
        enquire = xapian.Enquire(db)
        enquire.set_query(make_query(query))
        count = 40
        matches = enquire.get_mset(0, count)
        estimated = matches.get_matches_estimated()
        total = db.get_doccount()
        out = StringIO()
        print >>out, '''
    <html>
    <head><title>Results</title></head>
    <body>
    <h1>Results for "<b>%s</b>"</h1>
    ''' % query
        if estimated == 0:
            print >>out, "No results found."
        else:
            # Give as results the first 30 documents; also use them as the key
            # ones to use to compute relevant terms
            rset = xapian.RSet()
            for m in enquire.get_mset(0, 30):
                rset.add_document(m.document.get_docid())
            # Compute the tag cloud
            class NonTagFilter(xapian.ExpandDecider):
                def __call__(self, term):
                    return not term[0].isupper() and not term[0].isdigit()
            cloud = []
            maxscore = None
            for res in enquire.get_eset(40, rset, NonTagFilter()):
                # Normalise the score in the interval [0, 1]
                weight = math.log(res.weight)
                if maxscore == None: maxscore = weight
                tag = res.term
                cloud.append([tag, float(weight) / maxscore])
            max_weight = cloud[0][1]
            min_weight = cloud[-1][1]
            cloud.sort(key=lambda x:x[0])
            def mklink(query, term):
                return "/query?query=%s" % urllib.quote_plus(query + " and " + term)
            print >>out, "<h2>Tag cloud</h2>"
            print >>out, "<blockquote>"
            for term, weight in cloud:
                size = 100 + 100.0 * (weight - min_weight) / (max_weight - min_weight)
                print >>out, "<a href='%s' style='font-size:%d%%; color:brown;'>%s</a>" % (mklink(query, term), size, term)
            print >>out, "</blockquote>"
            print >>out, "<h2>Results</h2>"
            print >>out, "<p><a href='/'>Search again</a></p>"
            print >>out, "<p>%d results over %d documents, %.2f%%</p>" % (estimated, total, estimated * 100.0 / total)
            print >>out, "<p>%d/%d results</p>" % (matches.size(), estimated)
            print >>out, "<ul>"
            for m in matches:
                rec = data[m.document.get_data()]
                print >>out, "<li><a href='/item/%s'>%s</a></li>" % (rec["id"], rec["text"])
            print >>out, "</ul>"
            fd = open(QUERYLOG, "a")
            qinfo = dict(q=query, count=estimated)
            pickle.dump(qinfo, fd)
            fd.close()
        print >>out, '''
    <a href="/">Search again</a>
    
    </body>
    </html>'''
        return out.getvalue()
    @route("/item/:id")
    @route("/item/:id/")
    def show(id):
        rec = data[id]
        out = StringIO()
        print >>out, '''
    <html>
    <head><title>Result %s</title></head>
    <body>
    <h1>Raw JSON record for twit %s</h1>
    <pre>''' % (rec["id"], rec["id"])
        print >>out, simplejson.dumps(rec, indent=" ")
        print >>out, '''
    </pre>
    </body>
    </html>'''
        return out.getvalue()
    @route("/catinfo/:name")
    @route("/catinfo/:name/")
    def catinfo(name):
        prefix = prefixes[name]
        out = StringIO()
        print >>out, '''
    <html>
    <head><title>Values for %s</title></head>
    <body>
    ''' % name
        terms = [(x.term[len(prefix):], db.get_termfreq(x.term)) for x in db.allterms(prefix)]
        terms.sort(key=lambda x:x[1], reverse=True)
        freq_min = terms[0][1]
        freq_max = terms[-1][1]
        def mklink(name, term):
            return "/query?query=%s" % urllib.quote_plus(name + ":" + term)
        # Build tag cloud
        print >>out, "<h1>Tag cloud</h1>"
        print >>out, "<blockquote>"
        for term, freq in sorted(terms[:20], key=lambda x:x[0]):
            size = 100 + 100.0 * (freq - freq_min) / (freq_max - freq_min)
            print >>out, "<a href='%s' style='font-size:%d%%; color:brown;'>%s</a>" % (mklink(name, term), size, term)
        print >>out, "</blockquote>"
        print >>out, "<h1>All terms</h1>"
        print >>out, "<table>"
        print >>out, "<tr><th>Occurrences</th><th>Name</th></tr>"
        for term, freq in terms:
            print >>out, "<tr><td>%d</td><td><a href='/query?query=%s'>%s</a></td></tr>" % (freq, urllib.quote_plus(name + ":" + term), term)
        print >>out, "</table>"
        print >>out, '''
    </body>
    </html>'''
        return out.getvalue()
    # Change here for bind host and port
    bottle.run(host="0.0.0.0", port=8024)
    
    ...and then we presented our work and ended up winning the contest. This was the story of how we wrote this set of award winning code.

    27 September 2010

    Kees Cook: new RSA4096 key

    As part of the Ubuntu Security Team s overall OpenPGP key transition plans, I ve generated a new GPG key (DC6DC026). If you ve signed my old key (17063E6D), I d appreciate it if you could review my signed transition statement and sign my new key too. :) Thanks!

    23 September 2010

    Dirk Eddelbuettel: R Project and Google Summer of Code: Wrapping up

    As this year's admin, I wrote up the following summary which has now been posted at the R site in the appropriate slot. My thanks to this year's students, fellow mentors and everybody else who helped to make it happen. GSoC 2010 logo

    Projects 2010 As in 2008 and 2009, the R Project has again participated in the Google Summer of Code during 2010. Based on ideas collected and disussed on the R Wiki, the projects and students listed below (and sorted alphabetically by student) were selected for participation and have been sponsored by Google during the summer 2010. The finished projects are available via the R / GSoC 2010 repository at Google Code, and in several cases also via their individual repos (see below). Informal updates and final summaries on the work was also provided via the GSoC 2010 R group blog.

    rdx - Automatic Differentiation in R Chidambaram Annamalai, mentored by John Nash. Proposal: radx is a package to compute derivatives (of any order) of native R code for multivariate functions with vector outputs, f:R^m -> R^n, through Automatic Differentiation (AD). Numerical evaluation of derivatives has widespread uses in many fields. rdx will implement two modes for the computation of derivatives, the Forward and Reverse modes of AD, combining which we can efficiently compute Jacobians and Hessians. Higher order derivatives will be evaluated through Univariate Taylor Propagation. Delivered: Two packages radx: forward automatic differentiation in R and tada: templated automatic differentiation in C++ were created; see this blog post for details.

    A GUI for Graphics using ggplot and Deducer by Ian Fellows, mentored by Hadley Wickham. Proposal: R puts the latest statistical techniques at one's fingertips through thousands of add-on packages available on the CRAN download servers. The price for all of this power is complexity. Deducer is a cross-platform cross-console graphical user interface built on top of R designed to reduce this complexity. This project proposes to extend the scope of Deducer by creating an innovative yet intuitive system for generating statistical graphics based on the ggplot2 package. Delivered: All of the major features have been implemented, and are outlined in the video links in this blog post.

    rgeos - an R wrapper for GEOS by Colin Rundel, mentored by Roger Bivand. Proposal: At present there does not exist a robust geometry engine available to R, the tools that are available tend to be limited in scope and do not easily integrate with existing spatial analysis tools. GEOS is a powerful open source geometry engine written in C++ that implements spatial functions and operators from the OpenGIS Simple Features for SQL specification. rgeos will make these tools available within R and will integrate with existing spatial data tools through the sp package. Delivered: The rgeos project on R-Forge; see the final update blog post.

    Social Relations Analyses in R by Felix Schoenbrodt, mentored by Stefan Schmukle. Proposal: Social Relations Analyses (SRAs; Kenny, 1994) are a hot topic both in personality and in social psychology. While more and more research groups adopt the methodology, software solutions are lacking far behind - the main software for calculating SRAs are two DOS programs from 1995, which have a lot of restrictions. My GSOC project will extend the functionality of these existing programs and bring the power of SRAs into the R Environment for Statistical Computing as a state-of-the-art package. Delivered: The TripleR package is now on CRAN and hosted on RForge.Net; see this blog post for updates.

    NoSQL Interface for R by Yasuhisa Yoshida, mentored by Dirk Eddelbuettel. Proposal: So-called NoSQL databases are becoming increasingly popular. They generally provide very efficient lookup of key/value pairs. I'll provide several implementation of NoSQL interface for R. Beyond a sample interface package, I'll try to support generic interface similar to what the DBI package does for SQL backends Status: An initial prototype is available via RTokyoCabinet on Github. No updates were made since June; no communication occurred with anybody related to the GSoC project since June and the project earned a fail.

    Last modified: Wed Sep 22 19:39:43 CDT 2010

    18 September 2010

    Evgeni Golov: How to bypass DNS-based spam-filters using DNS

    I ve been sitting on this one since more than a month. I ve contacted upstream on the 19.08.2010 and the Debian maintainer on the 02.09.2010. No reaction from them till today, and no, my spamfilter does not eat mail ;) Still, I won t tell you the name of the software (but you could easily guess or check ) So let s put the grey hat on and begin ;) Foreword: when I write spam-filter, I mean some DNSBL/SPF/blah filter, not SpamAssassin, crm114 or other content-based filters. common spam-filters There are plenty of spam-filters out there which work after the following schema:
    for check in checks:
        if check(mail) == BAD:
            reject(mail)
            break
    And the checks often look like this:
    def check(mail):
        errors = False
        result = some_magic(mail)
        if not errors: return result
        else: return GOOD
    Here some_magic is a function that do the actual checks (DNSBL lookups etc) and which stores possible happened errors in errors. If an error occurred, it s safer to say the mail was good (or at least not bad) than bad. the problem This looks like a sane approach on the first sight: iterate over all checks and execute them until a mail is found to be spam (and the corresponding check did not end up in an error (imagine some weird DNS error for DNSBL or SPF checks here)). But then the author realizes that the errors might be global , like with DNS: when the first check notices that it can t resolve anything (ie. it ran into a DNS timeout three times in a row), the second check (which also utilizes DNS queries) will most probably result in an error too. After this he adds a global counter for DNS errors and skips all the checks that use DNS if this counter is >=3. Great idea , you say, saving resources is good . Bad idea , I say The reason is simple: DNSError != DNSError. Why? The local resolver might be broken, then every DNS query will end up with an error and DNS-based checks should be really disabled. The first three (out of eg. ten) DNSBLs might be down, but that s not a reason to skip the other seven and the SPF check. Etc Now let s assume all configured DNSBLs are working properly, so is the local resolver and the checks are:
    checks = [check_HELO, check_SPF, check_DNSBL]
    How could one attack this filter? the attack Set up the following zone
    spam.example.com IN NS ns1.example.com
    spam.example.com IN NS ns2.example.com
    spam.example.com IN NS ns3.example.com
    spam2.example.com IN MX mx1.spam.example.com
    spam2.example.com IN MX mx2.spam.example.com
    spam2.example.com IN MX mx3.spam.example.com
    spam2.example.com IN MX mx4.spam.example.com
    ns1.example.com IN A 10.1.1.1
    ns2.example.com IN A 10.2.2.2
    ns3.example.com IN A 10.3.3.3
    and greet the to-be-spammed-MTA with EHLO client1.spam.example.com
    What happens? The spam-filter tries to resolve client1.spam.example.com in check_HELO to check whether the hostname matches the IP-address the connection is coming from, fails three times (there are no reachable DNS servers in 10.0.0.0/8) and continues with the next two checks, but these are skipped because of previous DNS errors. As no checks could identify the mail as being spam, the mail is delivered to the users mailbox. With some creativity this can also be used in SPF records (via spam2.example.com), sender-domains etc. conclusion If you want to save resources by skipping DNS-based checks after another (DNS-based) check failed don t! Think whether this is really the same error you are seeing Additionally this can be used as a sort of DoS against the not said software: according to the logs each of my tries needed between 30 and 36 seconds (!) to complete imagine some hundred simultaneous requests the end You think I did something wrong with that post? Throw the first stone then, I don t care.

    12 September 2010

    Francois Marier: Setting up your own DNSSEC-aware resolver using Unbound

    Now that the root DNS servers are signed, I thought it was time I started using DNSSEC on my own PC. However, not wanting to wait for my ISP to enable it, I decided to setup a private recursive DNS resolver for myself using Unbound.

    Installing UnboundBeing already packaged in Debian and Ubuntu, unbound is only an apt-get away:
    apt-get install unbound
    though if you are running lenny, I suggest you grab the latest backport.

    Once unbound is installed, follow these instructions to enable DNSSEC.

    Optional settingsIn my /etc/unbound/unbound.conf, I enabled the following security options:
    harden-referral-path: yes
    use-caps-for-id: yes
    and turned on prefetching to hopefully keep in cache the sites I visit regularly:
    prefetch: yes
    prefetch-key: yes
    Finally, I also enabled statistics:
    extended-statistics: yes
    control-enable: yes
    control-interface: 127.0.0.1
    and ran sudo unbound-control-setup to generate the necessary keys.

    Once unbound is restarted (sudo /etc/init.d/unbound restart) stats can be queried to make sure that the DNS resolver is working:
    unbound-control stats

    Overriding DHCP settingsIn order to use my own unbound server for DNS lookups and not the one received via DHCP, I added this line to /etc/dhcp/dhclient.conf:
    supersede domain-name-servers 127.0.0.1;
    and restarted dhclient:
    sudo killall dhclient
    sudo killall dhclient
    sudo /etc/init.d/network-manager restart
    If you're not using DHCP, then you simply need to put this in your /etc/resolv.conf:
    nameserver 127.0.0.1

    Testing DNSSEC resolutionOnce everything is configured properly, the best way I found to test that this setup was actually working is to use a web browser to visit these sites:
    and using dig:
    $ dig +dnssec A www.dnssec.cz   grep ad
    ;; flags: qr rd ra ad; QUERY: 1, ANSWER: 2, AUTHORITY: 3, ADDITIONAL: 1

    Are there any other ways of making sure that DNSSEC is fully functional?

    4 September 2010

    Petter Reinholdtsen: Some notes on Flash in Debian and Debian Edu

    In the Debian popularity-contest numbers, the adobe-flashplugin package the second most popular used package that is missing in Debian. The sixth most popular is flashplayer-mozilla. This is a clear indication that working flash is important for Debian users. Around 10 percent of the users submitting data to popcon.debian.org have this package installed. In the report written by Lars Risan in August 2008 ( Skolelinux i bruk Rapport for Hurum kommune, Universitetet i Agder og stiftelsen SLX Debian Labs ), one of the most important problems schools experienced with Debian Edu/Skolelinux was the lack of working Flash. A lot of educational web sites require Flash to work, and lacking working Flash support in the web browser and the problems with installing it was perceived as a good reason to stay with Windows. I once saw a funny and sad comment in a web forum, where Linux was said to be the retarded cousin that did not really understand everything you told him but could work fairly well. This was a comment regarding the problems Linux have with proprietary formats and non-standard web pages, and is sad because it exposes a fairly common understanding of whose fault it is if web pages that only work in for example Internet Explorer 6 fail to work on Firefox, and funny because it explain very well how annoying it is for users when Linux distributions do not work with the documents they receive or the web pages they want to visit. This is part of the reason why I believe it is important for Debian and Debian Edu to have a well working Flash implementation in the distribution, to get at least popular sites as Youtube and Google Video to working out of the box. For Squeeze, Debian have the chance to include the latest version of Gnash that will make this happen, as the new release 0.8.8 was published a few weeks ago and is resting in unstable. The new version work with more sites that version 0.8.7. The Gnash maintainers have asked for a freeze exception, but the release team have not had time to reply to it yet. I hope they agree with me that Flash is important for the Debian desktop users, and thus accept the new package into Squeeze.

    26 August 2010

    David Paleino: gmtkbabel 0.1

    Version 0.1 of gmtkbabel has just been released! :) It consists of a set of shell scripts, which use zenity to give a nice GUI over mtkbabel. gmtkbabel 0.1 Future improvements might include providing a Qt alternative (and the "g" in the name might just mean "GUI" instead of "GTK" then), and whatever users need. It might also become something more serious, written in a more complex language, who knows :) Many thank to Elena of Valhalla'' Grandi, who started this project to help some users on #osm-it@oftc.

    20 August 2010

    Riku Voipio: (unnofficial) Bits from ARM porters

    Quite a few things have happened recently in the Debian/ARM land

    ARM and Canonical have generously provided us with bunch of fast armel machines. Four of these are now as buildd's, bringing the total of armel buildd's to 7. In other words, armel should no longer lag behind other architectures when building unstable packages.

    One of machines, abel.debian.org has been setup as a porter box. It is faster (around 3x) than the older porterbox (agricola). All Debian Developers have access to the porterboxes.

    The new buildds have allowed us to enable more suites. Thanks to Philipp Kerns work, armel builds now experimental, lenny-volatile, lenny-backports as well as unstable/non-free. Especially if you are using stable Debian, access to backports and volatile should make life happier :)

    Finally, the next big thing is Hardfloat ARM port, effort being lead by Konstantinos Margaritis. This doesn't mean that the armel port is going away. Majority of ARM cpus sold are still without FPU, so the softloaf port (armel) will still have a long life ahead. Meanwhile, the armhf port will provide a more optimal platform for people with bleeding edge ARM cores (ARMv7 + vfp). Some people have been unhappy with the new proposed new port, and various alternatives have been proposed. However, armhf is currently the only solution being actively worked on.

    Update: thank canonical too

    1 August 2010

    Rapha&#235;l Hertzog: First Flattr FOSS Suggestions

    Flattr FLOSS LogoThe Flattr FOSS project is quite young so very few free software are currently listed in the dedicated directories. It s still advocacy time: if there are free software that you d like to flattr, please tell them and point them to Flattr FOSS. It s too early for any conclusion, but the feedback from users is good and it looks like that people using flattr to support free software are more generous than the average flattr user. You re great people! :-) Anyway, it s time for me to give a few suggestions of projects to flattr.
    1. My first recommendation is Project Hamster, it s a time-tracking application for GNOME but it has come a long way thanks to the work of Toms Bau is. I use everyday and it rocks.
    2. My second recommendation is verallt, it s a Firefox extension that allows usage of Flattr even in places where it was not designed to be used: forums, mailing list archives, etc. The persons using Flattr just put [Flattr=20693] in their signature and the Firefox extension automatically replaces this text with a real Flattr button ready to be clicked. Thanks to Paul Da Silva for the nice idea and the first implementation!
    3. My third recommendation is Mustard, it s a StatusNet client for the Android platform. More concretely you can install it on your Android phone to send updates to identi.ca while traveling. I have no Android phone but Mustard seems to be popular among owners of such phones!
    4. My fourth recommendation is moreutils from Joey Hess. It s set of unix (command line) tools that nobody else thought of writing when unix was young (according to Joey himself). They are all very useful, I use more or less regularly isutf8 (verify if a file is UTF-8 compliant), combine (logical operations on lines of two files), pee (send standard input to two programs, very useful in git hooks when you want to run two programs that both consume the same data), sponge (ever tried grep -v foo file >file and lost your data? now you can use grep -v foo file sponge file ). And Joey is a long time Debian developer who has truly shaped Debian, he s behind several major Debian projects (debconf, debian-installer, debhelper, ). Big kudos to him!
    5. My last recommendation is to flattr Andreas Gohr for his work as dokuwiki lead developer. There s no flattr button on dokuwiki s website but you ll find some in Andreas blog, just pick a dokuwiki related article like this one: Dokuwiki Birthday Bughunting Weekend. Dokuwiki is a simple wiki that works without any database (the pages are stored in flat files) and it s even commonly used to setup simple websites thanks to the numerous themes available.
    Okay, that s it for this month. I ll try to keep a broad panel of software (desktop, command line, mobile, web, etc.). Since I have promoted a GNOME desktop application, I would like to be able to promote a KDE or XFCE application next month but I did not discover any KDE/XFCE project using Flattr do you know any? Please share in the comments if you find some. Also I wonder if you have decided of a flattr strategy Personally I m likely to flattr my favorites projects/persons each month and to flattr a few other occasionally as I discover them. What s your own strategy? Flattr this Share/Bookmark 4 comments Support my work

    17 July 2010

    Petter Reinholdtsen: What are they searching for - PowerDNS and ISC DHCP in LDAP

    This is a followup on my previous work on merging all the computer related LDAP objects in Debian Edu. As a step to try to see if it possible to merge the DNS and DHCP LDAP objects, I have had a look at how the packages pdns-backend-ldap and dhcp3-server-ldap in Debian use the LDAP server. The two implementations are quite different in how they use LDAP. To get this information, I started slapd with debugging enabled and dumped the debug output to a file to get the LDAP searches performed on a Debian Edu main-server. Here is a summary. powerdns Clues on how to set up PowerDNS to use a LDAP backend is available on the web. PowerDNS have two modes of operation using LDAP as its backend. One "strict" mode where the forward and reverse DNS lookups are done using the same LDAP objects, and a "tree" mode where the forward and reverse entries are in two different subtrees in LDAP with a structure based on the DNS names, as in tjener.intern and 2.2.0.10.in-addr.arpa. In tree mode, the server is set up to use a LDAP subtree as its base, and uses a "base" scoped search for the DNS name by adding "dc=tjener,dc=intern," to the base with a filter for "(associateddomain=tjener.intern)" for the forward entry and "dc=2,dc=2,dc=0,dc=10,dc=in-addr,dc=arpa," with a filter for "(associateddomain=2.2.0.10.in-addr.arpa)" for the reverse entry. For forward entries, it is looking for attributes named dnsttl, arecord, nsrecord, cnamerecord, soarecord, ptrrecord, hinforecord, mxrecord, txtrecord, rprecord, afsdbrecord, keyrecord, aaaarecord, locrecord, srvrecord, naptrrecord, kxrecord, certrecord, dsrecord, sshfprecord, ipseckeyrecord, rrsigrecord, nsecrecord, dnskeyrecord, dhcidrecord, spfrecord and modifytimestamp. For reverse entries it is looking for the attributes dnsttl, arecord, nsrecord, cnamerecord, soarecord, ptrrecord, hinforecord, mxrecord, txtrecord, rprecord, aaaarecord, locrecord, srvrecord, naptrrecord and modifytimestamp. The equivalent ldapsearch commands could look like this:
    ldapsearch -h ldap \
      -b dc=tjener,dc=intern,ou=hosts,dc=skole,dc=skolelinux,dc=no \
      -s base -x '(associateddomain=tjener.intern)' dNSTTL aRecord nSRecord \
      cNAMERecord sOARecord pTRRecord hInfoRecord mXRecord tXTRecord \
      rPRecord aFSDBRecord KeyRecord aAAARecord lOCRecord sRVRecord \
      nAPTRRecord kXRecord certRecord dSRecord sSHFPRecord iPSecKeyRecord \
      rRSIGRecord nSECRecord dNSKeyRecord dHCIDRecord sPFRecord modifyTimestamp
    ldapsearch -h ldap \
      -b dc=2,dc=2,dc=0,dc=10,dc=in-addr,dc=arpa,ou=hosts,dc=skole,dc=skolelinux,dc=no \
      -s base -x '(associateddomain=2.2.0.10.in-addr.arpa)'
      dnsttl, arecord, nsrecord, cnamerecord soarecord ptrrecord \
      hinforecord mxrecord txtrecord rprecord aaaarecord locrecord \
      srvrecord naptrrecord modifytimestamp
    
    In Debian Edu/Lenny, the PowerDNS tree mode is used with ou=hosts,dc=skole,dc=skolelinux,dc=no as the base, and these are two example LDAP objects used there. In addition to these objects, the parent objects all th way up to ou=hosts,dc=skole,dc=skolelinux,dc=no also exist.
    dn: dc=tjener,dc=intern,ou=hosts,dc=skole,dc=skolelinux,dc=no
    objectclass: top
    objectclass: dnsdomain
    objectclass: domainrelatedobject
    dc: tjener
    arecord: 10.0.2.2
    associateddomain: tjener.intern
    dn: dc=2,dc=2,dc=0,dc=10,dc=in-addr,dc=arpa,ou=hosts,dc=skole,dc=skolelinux,dc=no
    objectclass: top
    objectclass: dnsdomain2
    objectclass: domainrelatedobject
    dc: 2
    ptrrecord: tjener.intern
    associateddomain: 2.2.0.10.in-addr.arpa
    
    In strict mode, the server behaves differently. When looking for forward DNS entries, it is doing a "subtree" scoped search with the same base as in the tree mode for a object with filter "(associateddomain=tjener.intern)" and requests the attributes dnsttl, arecord, nsrecord, cnamerecord, soarecord, ptrrecord, hinforecord, mxrecord, txtrecord, rprecord, aaaarecord, locrecord, srvrecord, naptrrecord and modifytimestamp. For reverse entires it also do a subtree scoped search but this time the filter is "(arecord=10.0.2.2)" and the requested attributes are associateddomain, dnsttl and modifytimestamp. In short, in strict mode the objects with ptrrecord go away, and the arecord attribute in the forward object is used instead. The forward and reverse searches can be simulated using ldapsearch like this:
    ldapsearch -h ldap -b ou=hosts,dc=skole,dc=skolelinux,dc=no -s sub -x \
      '(associateddomain=tjener.intern)' dNSTTL aRecord nSRecord \
      cNAMERecord sOARecord pTRRecord hInfoRecord mXRecord tXTRecord \
      rPRecord aFSDBRecord KeyRecord aAAARecord lOCRecord sRVRecord \
      nAPTRRecord kXRecord certRecord dSRecord sSHFPRecord iPSecKeyRecord \
      rRSIGRecord nSECRecord dNSKeyRecord dHCIDRecord sPFRecord modifyTimestamp
    ldapsearch -h ldap -b ou=hosts,dc=skole,dc=skolelinux,dc=no -s sub -x \
      '(arecord=10.0.2.2)' associateddomain dnsttl modifytimestamp
    
    In addition to the forward and reverse searches , there is also a search for SOA records, which behave similar to the forward and reverse lookups. A thing to note with the PowerDNS behaviour is that it do not specify any objectclass names, and instead look for the attributes it need to generate a DNS reply. This make it able to work with any objectclass that provide the needed attributes. The attributes are normally provided in the cosine (RFC 1274) and dnsdomain2 schemas. The latter is used for reverse entries like ptrrecord and recent DNS additions like aaaarecord and srvrecord. In Debian Edu, we have created DNS objects using the object classes dcobject (for dc), dnsdomain or dnsdomain2 (structural, for the DNS attributes) and domainrelatedobject (for associatedDomain). The use of structural object classes make it impossible to combine these classes with the object classes used by DHCP. There are other schemas that could be used too, for example the dnszone structural object class used by Gosa and bind-sdb for the DNS attributes combined with the domainrelatedobject object class, but in this case some unused attributes would have to be included as well (zonename and relativedomainname). My proposal for Debian Edu would be to switch PowerDNS to strict mode and not use any of the existing objectclasses (dnsdomain, dnsdomain2 and dnszone) when one want to combine the DNS information with DHCP information, and instead create a auxiliary object class defined something like this (using the attributes defined for dnsdomain and dnsdomain2 or dnszone):
    objectclass ( some-oid NAME 'dnsDomainAux'
        SUP top
        AUXILIARY
        MAY ( ARecord $ MDRecord $ MXRecord $ NSRecord $ SOARecord $ CNAMERecord $
              DNSTTL $ DNSClass $ PTRRecord $ HINFORecord $ MINFORecord $
              TXTRecord $ SIGRecord $ KEYRecord $ AAAARecord $ LOCRecord $
              NXTRecord $ SRVRecord $ NAPTRRecord $ KXRecord $ CERTRecord $
              A6Record $ DNAMERecord
        ))
    
    This will allow any object to become a DNS entry when combined with the domainrelatedobject object class, and allow any entity to include all the attributes PowerDNS wants. I've sent an email to the PowerDNS developers asking for their view on this schema and if they are interested in providing such schema with PowerDNS, and I hope my message will be accepted into their mailing list soon. ISC dhcp The DHCP server searches for specific objectclass and requests all the object attributes, and then uses the attributes it want. This make it harder to figure out exactly what attributes are used, but thanks to the working example in Debian Edu I can at least get an idea what is needed without having to read the source code. In the DHCP server configuration, the LDAP base to use and the search filter to use to locate the correct dhcpServer entity is stored. These are the relevant entries from /etc/dhcp3/dhcpd.conf:
    ldap-base-dn "dc=skole,dc=skolelinux,dc=no";
    ldap-dhcp-server-cn "dhcp";
    
    The DHCP server uses this information to nest all the DHCP configuration it need. The cn "dhcp" is located using the given LDAP base and the filter "(&(objectClass=dhcpServer)(cn=dhcp))". The search result is this entry:
    dn: cn=dhcp,dc=skole,dc=skolelinux,dc=no
    cn: dhcp
    objectClass: top
    objectClass: dhcpServer
    dhcpServiceDN: cn=DHCP Config,dc=skole,dc=skolelinux,dc=no
    
    The content of the dhcpServiceDN attribute is next used to locate the subtree with DHCP configuration. The DHCP configuration subtree base is located using a base scope search with base "cn=DHCP Config,dc=skole,dc=skolelinux,dc=no" and filter "(&(objectClass=dhcpService)( (dhcpPrimaryDN=cn=dhcp,dc=skole,dc=skolelinux,dc=no)(dhcpSecondaryDN=cn=dhcp,dc=skole,dc=skolelinux,dc=no)))". The search result is this entry:
    dn: cn=DHCP Config,dc=skole,dc=skolelinux,dc=no
    cn: DHCP Config
    objectClass: top
    objectClass: dhcpService
    objectClass: dhcpOptions
    dhcpPrimaryDN: cn=dhcp, dc=skole,dc=skolelinux,dc=no
    dhcpStatements: ddns-update-style none
    dhcpStatements: authoritative
    dhcpOption: smtp-server code 69 = array of ip-address
    dhcpOption: www-server code 72 = array of ip-address
    dhcpOption: wpad-url code 252 = text
    
    Next, the entire subtree is processed, one level at the time. When all the DHCP configuration is loaded, it is ready to receive requests. The subtree in Debian Edu contain objects with object classes top/dhcpService/dhcpOptions, top/dhcpSharedNetwork/dhcpOptions, top/dhcpSubnet, top/dhcpGroup and top/dhcpHost. These provide options and information about netmasks, dynamic range etc. Leaving out the details here because it is not relevant for the focus of my investigation, which is to see if it is possible to merge dns and dhcp related computer objects. When a DHCP request come in, LDAP is searched for the MAC address of the client (00:00:00:00:00:00 in this example), using a subtree scoped search with "cn=DHCP Config,dc=skole,dc=skolelinux,dc=no" as the base and "(&(objectClass=dhcpHost)(dhcpHWAddress=ethernet 00:00:00:00:00:00))" as the filter. This is what a host object look like:
    dn: cn=hostname,cn=group1,cn=THINCLIENTS,cn=DHCP Config,dc=skole,dc=skolelinux,dc=no
    cn: hostname
    objectClass: top
    objectClass: dhcpHost
    dhcpHWAddress: ethernet 00:00:00:00:00:00
    dhcpStatements: fixed-address hostname
    
    There is less flexiblity in the way LDAP searches are done here. The object classes need to have fixed names, and the configuration need to be stored in a fairly specific LDAP structure. On the positive side, the invidiual dhcpHost entires can be anywhere without the DN pointed to by the dhcpServer entries. The latter should make it possible to group all host entries in a subtree next to the configuration entries, and this subtree can also be shared with the DNS server if the schema proposed above is combined with the dhcpHost structural object class. Conclusion The PowerDNS implementation seem to be very flexible when it come to which LDAP schemas to use. While its "tree" mode is rigid when it come to the the LDAP structure, the "strict" mode is very flexible, allowing DNS objects to be stored anywhere under the base cn specified in the configuration. The DHCP implementation on the other hand is very inflexible, both regarding which LDAP schemas to use and which LDAP structure to use. I guess one could implement ones own schema, as long as the objectclasses and attributes have the names used, but this do not really help when the DHCP subtree need to have a fairly fixed structure. Based on the observed behaviour, I suspect a LDAP structure like this might work for Debian Edu:
    ou=services
      cn=machine-info (dhcpService) - dhcpServiceDN points here
        cn=dhcp (dhcpServer)
        cn=dhcp-internal (dhcpSharedNetwork/dhcpOptions)
          cn=10.0.2.0 (dhcpSubnet)
            cn=group1 (dhcpGroup/dhcpOptions)
        cn=dhcp-thinclients (dhcpSharedNetwork/dhcpOptions)
          cn=192.168.0.0 (dhcpSubnet)
            cn=group1 (dhcpGroup/dhcpOptions)
        ou=machines - PowerDNS base points here
          cn=hostname (dhcpHost/domainrelatedobject/dnsDomainAux)
    
    This is not tested yet. If the DHCP server require the dhcpHost entries to be in the dhcpGroup subtrees, the entries can be stored there instead of a common machines subtree, and the PowerDNS base would have to be moved one level up to the machine-info subtree. The combined object under the machines subtree would look something like this:
    dn: dc=hostname,ou=machines,cn=machine-info,dc=skole,dc=skolelinux,dc=no
    dc: hostname
    objectClass: top
    objectClass: dhcpHost
    objectclass: domainrelatedobject
    objectclass: dnsDomainAux
    associateddomain: hostname.intern
    arecord: 10.11.12.13
    dhcpHWAddress: ethernet 00:00:00:00:00:00
    dhcpStatements: fixed-address hostname.intern
    
    One could even add the LTSP configuration associated with a given machine, as long as the required attributes are available in a auxiliary object class.

    Next.

    Previous.